gpt4 book ai didi

go - 在编码为 JSON 之前将结构转换为不同的结构

转载 作者:行者123 更新时间:2023-12-01 22:32:03 25 4
gpt4 key购买 nike

我正在尝试使用围棋作为后端来实现棋盘游戏,并且遇到了一些障碍,并且试图了解以围棋方式解决此问题的最佳方法是什么。
我有一个复杂的结构,代表我在游戏引擎中使用的游戏状态,以评估状态以及每个 Action 将做什么以及它将如何影响游戏。

type Game struct {
ID string
Name string `json:"name"`
Version Version `json:"version"`
StartingMode StartingMode `json:"startingMode"`
Players []*Player `json:"players"`
GameMap *BoardMap `json:"gameMap"`
Countries map[string]*country `json:"countries"`
Config *Config `json:"config"`
TurnPlayer *Player `json:"turnPlayer"` //represents the player who started the turn
TurnCountry *country `json:"turnCountry"` //represents the country which started the turn
CurrentPlayer *Player `json:"currentPlayer"` //represents the current player to action
GameStart bool `json:"gameStart"`
GameFinish bool `json:"gameFinish"`
InAuction bool `json:"inAuction"` //represents the game is in the auction stage
GameSettings Settings `json:"settings"`
}
现在,我可以将它编码为 JSON 并将其保存在我的数据库中,它工作正常,但是当我必须将它发送到前端时,它并不能真正工作。前端也不需要知道那么多信息,我真的想要一些更简单的东西,例如:
type OtherGame struct {
players []*OtherPlayer
countries []*OtherCountry
map []*OtherArea
}
所以,我想我必须编写一些转换器函数,然后编码这个 OtherGame 结构,或 我是否应该只编写一个自定义函数来迭代 Game 中的不同结构并使用 Sprintf 将它们放入字符串中?

最佳答案

我经常使用这种设计模式来为特定的处理程序生成自定义输出。在那里定义您的 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

关于go - 在编码为 JSON 之前将结构转换为不同的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63871646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com