Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 在编组为JSON之前,将结构转换为不同的结构_Go - Fatal编程技术网

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

Go 在编组为JSON之前,将结构转换为不同的结构,go,Go,我正在尝试使用go作为后端来实现一个boardgame,我遇到了一个阻碍因素,我正在尝试了解用go方式解决这个问题的最佳方法是什么 我有一个复杂的结构,它代表我在游戏引擎中使用的游戏状态,用来评估状态,以及每个动作将做什么,以及它将如何影响游戏 type Game struct { ID string Name string `json:"name"` Version Ver

我正在尝试使用go作为后端来实现一个boardgame,我遇到了一个阻碍因素,我正在尝试了解用go方式解决这个问题的最佳方法是什么

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

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并保存在我的DB中,它工作得很好,但是当我必须将它发送到前端时,它实际上不起作用。另外,前端不需要知道那么多信息,我真的想要一些更简单的东西,例如:

type OtherGame struct {
 players []*OtherPlayer
 countries []*OtherCountry
 map []*OtherArea
}

所以,我想我必须编写一些转换函数,然后封送另一个游戏结构,或者我是否应该编写一个自定义函数,迭代到游戏中的不同结构,并使用Sprintf将它们放入字符串中?

您可以编写一个
方法
,将您的
游戏
数据转换为
其他游戏
。像这样的

func(游戏)OtherGame()OtherGame{
返回其他游戏{
玩家:游戏,玩家,
国家:游戏。国家,
}
}
在发送到
前端之前调用此方法

game:=game{…}
otherGame:=游戏。otherGame()

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

这部分回答了您的问题吗?