0

I've seen some go code that looks like this :

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)
}

I find two functions redundant. Is there a simpler way to merge those two into a more generic function? Is it good practice in Go?

0

1 Answer 1

3
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)
}

Then use it as so:

var body emailForm
if err := decodeForm(r, &body); err != nil {
    panic(err)
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, that seems way cleaner than what I coded. Is it good practice to go through interface like that ?
@AdoRen: It's the way json works, so it's not only good practice, it's essentially the only way :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.