猿问

在编组为 JSON 之前将结构转换为不同的结构

我正在尝试使用围棋作为后端来实现棋盘游戏,并且遇到了一些障碍,并且试图了解以围棋方式解决此问题的最佳方法是什么。


我有一个复杂的结构,代表我在游戏引擎中使用的游戏状态,以评估状态以及每个动作将做什么以及它将如何影响游戏。


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 将它们放入字符串中?



月关宝盒
浏览 105回答 2
2回答

眼眸繁星

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

慕运维8079593

您可以编写一个method将您的Game数据转换为OtherGame. 像这样的东西。func (game Game) OtherGame() OtherGame {    return OtherGame{        players:   game.Players,        countries: game.Countries,    }}在发送到 之前调用此方法front-end。game := Game{...}otherGame := game.OtherGame()
随时随地看视频慕课网APP

相关分类

Go
我要回答