在Go语言中处理JSON的最佳实践

huangapple go评论112阅读模式
英文:

Best practices working with JSON in Go

问题

我正在开始编写一个使用Go语言的聊天应用程序,并开始思考如何最好地处理JSON。我已经阅读了不同的文章,似乎我必须为客户端发送的每个操作创建一个不同的类型。

假设有三个操作:

  • NewMessage(新消息)
  • DeleteMessage(删除消息)
  • EditMessage(编辑消息)

据我理解,我必须创建三个与这些操作匹配的类型。类似于这样:

  1. type Message struct {
  2. Action string `json:"action"`
  3. Data map[string]*json.RawMessage `json:"data"`
  4. }
  5. type MessageMeta struct {
  6. UserId int `json:"user_id"`
  7. ChannelID int `json:"channel_id"`
  8. }
  9. type NewMessageAction struct {
  10. MessageMeta
  11. Message string `json:"message"`
  12. }
  13. type EditMessageAction struct {
  14. MessageMeta
  15. MessageId int `json:"message_id"`
  16. Message string `json:"message"`
  17. }
  18. type DeleteMessageAction struct {
  19. MessageMeta
  20. MessageId int `json:"message_id"`
  21. }

我来自Node.js世界(虽然我不想比较这两者),对我来说,为每个操作创建和维护一个类型似乎有点冗长。如果有成百上千个操作怎么办?

英文:

I'm in the beginning of writing a chat app in Go and started wondering what is the best way working with JSON. I've read different articles and it seems like I have to create a different type for every action the client sends.

Lets say there are three actions:

  1. NewMessage
  2. DeleteMessage
  3. EditMessage

To my understanding I have to create three types that match these actions. Something like this:

  1. type Message struct {
  2. Action string `json:"action"`
  3. Data map[string]*json.RawMessage `json:"data"`
  4. }
  5. type MessageMeta struct {
  6. UserId int `json:"user_id"`
  7. ChannelID int `json:"channel_id"`
  8. }
  9. type NewMessageAction struct {
  10. MessageMeta
  11. Message string `json:"message"`
  12. }
  13. type EditMessageAction struct {
  14. MessageMeta
  15. MessageId int `json:"message_id"`
  16. Message string `json:"message"`
  17. }
  18. type DeleteMessageAction struct {
  19. MessageMeta
  20. MessageId int `json:"message_id"`
  21. }

I come from Node.js world (although I don't want to compare the two) and to me it seems a bit too verbose to create and maintain a type for every action there is. What if there are hundreds of actions?

答案1

得分: 2

Go是一种强类型的编程语言。它没有像JavaScript那样的松散类型。

如果你想为每个消息定义一个强类型的数据类型,那么你需要为每种类型编写一个结构体。否则,你可以将消息解组为map[string]interface{}(用于“通用”JSON对象),并使用它进行操作(这将需要类型断言将interface值转换为强类型)。

英文:

Go is a strongly typed programming language. There are no loose types like in JavaScript.

If you want a strong data type for each message, then you'll need to write a struct for each type. Otherwise you can unmarshal the message into a map[string]interface{} (for "generic" JSON objects) and work with that instead (which will require type assertions to convert the interface values into strong types).

huangapple
  • 本文由 发表于 2017年7月11日 19:05:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/45032773.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定