GoでJSONレスポンスに含めたくないデータがあるときの対処法

Go

ユーザーデータを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)
}