1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ユーザーデータをJSONで返すとして、その中にパスワードなどの返す必要のないデータが含まれていたときに、簡単に除外する方法がある。

たとえば、User構造体にパスワードが含まれていて、それをJSONレスポンスに含めたくない場合は、構造体のJSONタグにjson:"-"と書くと除外してくれる。

package main

import (
	"encoding/json"
	"net/http"
)

type User struct {
	ID       int    `json:"id"`
	Name     string `json:"name"`
	Age      int    `json:"age"`
	Email    string `json:"email"`
	Password string `json:"-"`
}

func main() {
	user := User{
		ID:       1,
		Name:     "Test Test",
		Age:      25,
		Email:    "test@example.com",
		Password: "password",
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// userをJSONに変換
		userJSON, err := json.Marshal(user)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// JSONをレスポンスとして返す
		w.Header().Set("Content-Type", "application/json")
		w.Write(userJSON)
	})

	http.ListenAndServe(":8080", nil)
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?