2 回答

TA貢獻1873條經驗 獲得超9個贊
我經常使用這種設計模式來為特定的處理程序生成自定義輸出。在那里定義您的 JSON 標簽,并且只公開您需要的內容。然后自定義類型與您的處理程序緊密耦合:
func gameHandler(w http.ResponseWriter, r *http.Request) {
g, err := dbLookupGame(r) // handle err
// define one-time anonymous struct for custom formatting
jv := struct {
ID string `json:"id"`
Name string `json:"name"`
Version string `json:"ver"`
}{
ID: g.ID,
Name: g.Name,
Version: g.Version,
}
err = json.NewEncoder(w).Encode(&jv) // handle err
}
type game struct {
ID string
Name string
Version string
Secret string // don't expose this
// other internals ...
}
https://play.golang.org/p/hhAAlmb51Ue

TA貢獻1876條經驗 獲得超5個贊
您可以編寫一個method將您的Game數據轉換為OtherGame. 像這樣的東西。
func (game Game) OtherGame() OtherGame {
return OtherGame{
players: game.Players,
countries: game.Countries,
}
}
在發送到 之前調用此方法front-end。
game := Game{...}
otherGame := game.OtherGame()
- 2 回答
- 0 關注
- 119 瀏覽
添加回答
舉報