gpt4 book ai didi

Go 结构分离最佳实践

转载 作者:行者123 更新时间:2023-12-01 19:20:11 24 4
gpt4 key购买 nike

我试图找出一种体面的方法来处理结构的多种用途。让我解释一下这个场景。

我有一个代表gorm中的模型的结构。在当前实现中,我将验证绑定(bind)到此结构,因此当请求到达端点时,我将针对模型的结构进行验证。这适用于大多数情况。但是在某些情况下,我希望对请求和响应有更多的控制权。

这可以通过引入一些额外的内部结构来解析请求和响应。我可以将验证从模型解耦到请求特定的结构中。我试图弄清楚围绕这些模式的最佳实践是什么。可以肯定,很多偷窥者都会面临类似的情况。

// Transaction holds the transaction details.
type Transaction struct {
Program Program
ProgramID uuid.UUID
Type string
Value float64
Reference string
}

// TransactionRequest for the endpoint.
type TransactionRequest struct {
ProgramKey string `json:"program_key" validator:"required"`
Type string `json:"type" validator:"required,oneof=credit debit"`
Value float64 `json:"value" validator:"required,numeric"`
Reference string `json:"reference" validator:"required"`
}

更新:

我设法通过为更新请求引入额外标签来找到平衡,我写了我是如何实现它的 here

最佳答案

我遇到了类似的问题,为了解决这个问题,定义了一种验证方法并且不使用标签。我必须这样做,因为我遵循 DDD,我们应该在服务层而不是 API 层进行验证。
这是我的方法示例:

type Station struct {
types.GormCol
CompanyID types.RowID `gorm:"not null;unique" json:"company_id,omitempty"`
CompanyName string `gorm:"not null;unique" json:"company_name,omitempty"`
NodeCode uint64 `json:"node_code,omitempty"`
NodeName string `json:"node_name,omitempty"`
Key string `gorm:"type:text" json:"key,omitempty"`
MachineID string `json:"machine_id,omitempty"`
Detail string `json:"detail,omitempty"`
Error error `sql:"-" json:"user_error,omitempty"`
Extra map[string]interface{} `sql:"-" json:"extra_station,omitempty"`
}

// Validate check the type of
func (p *Station) Validate(act action.Action) error {
fieldError := core.NewFieldError(term.Error_in_companys_form)

switch act {
case action.Save:
if p.CompanyName == "" {
fieldError.Add(term.V_is_required, "Company Name", "company_name")
}

if p.CompanyID == 0 {
fieldError.Add(term.V_is_required, "Company ID", "company_id")
}

}

if fieldError.HasError() {
return fieldError
}
return nil
}
文件地址: https://github.com/syronz/sigma-mono/blob/master/model/station.model.go

关于Go 结构分离最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61157969/

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