Golang领域驱动设计实体,包括在结构体中使用JSON属性。

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

golang domain driven design entities including json attributes in structs

问题

我正在使用DDD来设计我的Go应用程序。在实体层中,我将使用structs,它看起来像这样:

type FruitBasket struct {
    Id      int64  `json:"ref"`
    private string `json:"ttl"`
}

在DDD中,将json属性包含在这个struct中作为实体层是否可以?我更倾向于不这样做,但不确定。是否有其他替代方案我应该考虑?

英文:

I am using DDD to design my go application. In the entity layer, I will be using structs and it looks like this

type FruitBasket struct {
    Id      int64  `json:"ref"`
    private string `json:"ttl"`
}

Is it ok to include the json attributes in this struct which forms the entity layer in the DDD? I would prefer not to do it, but not sure. Is there any other alternative which I should consider?

答案1

得分: 1

通常,JSON 标签用于在 HTTP API 中取消编组请求并编组响应。

更具动态性的一种方法是使用特定的请求和响应结构,就像这个例子一样,我从 Mat Ryers 的文章《八年后,我如何编写 HTTP 服务》中找到的。

func (s *server) handleSomething() http.HandlerFunc {
    type request struct {
        Name string
    }
    type response struct {
        Greeting string `json:"greeting"`
    }
    return func(w http.ResponseWriter, r *http.Request) {
        ...
    }
}
英文:

Usually the JSON tags are used to unmarshal requests and marshal responses in HTTP APIs.

Something that gives you more dynamicity is having specific request and response structures like this example, which I took from Mat Ryers post of
How I write HTTP services after eight years.

func (s *server) handleSomething() http.HandlerFunc {
    type request struct {
        Name string
    }
    type response struct {
        Greeting string `json:"greeting"`
    }
    return func(w http.ResponseWriter, r *http.Request) {
        ...
    }
}

huangapple
  • 本文由 发表于 2021年6月2日 10:41:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/67798230.html
匿名

发表评论

匿名网友

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

确定