我见过一些看起来像这样的 go 代码:
type userForm struct {
Name string `json:"name" validate:"min=2"`
Surname string `json:"surname" validate:"min=2"`
Phone string `json:"phone" validate:"min=10"`
Email string `json:"email,omitempty" validate:"omitempty,email"`
}
type emailForm struct {
Email string `json:"email" validate:"email"`
}
func decodeUserForm(r *http.Request) (userForm, error) {
var body userForm
d := json.NewDecoder(r.Body)
if err := d.Decode(&body); err != nil {
return body, NewHTTPError(err, 400, "unable to decode user form")
}
return body, validateStruct(body)
}
func decodeEmailForm(r *http.Request) (emailForm, error) {
var body emailForm
d := json.NewDecoder(r.Body)
if err := d.Decode(&body); err != nil {
return body, NewHTTPError(err, 400, "unable to decode email form")
}
return body, validateStruct(body)
}
我发现两个功能是多余的。有没有更简单的方法将这两者合并成一个更通用的函数?围棋是好的做法吗?
慕斯709654
相关分类