猿问

如何使用 golang 进行通用解码

我见过一些看起来像这样的 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)

}

我发现两个功能是多余的。有没有更简单的方法将这两者合并成一个更通用的函数?围棋是好的做法吗?


交互式爱情
浏览 165回答 1
1回答

慕斯709654

func decodeForm(r *http.Request, dst interface{}) error {    if err := json.NewDecoder(r.Body).Decode(dst); err != nil {        return NewHTTPError(err, 400, "unable to decode email form")    }    return validateStruct(dst)}然后像这样使用它:var body emailFormif err := decodeForm(r, &body); err != nil {    panic(err)}
随时随地看视频慕课网APP

相关分类

Go
我要回答