go get int or string from req.Body dont use additional struct

Viewed 22

Frequent case: I want to get a single string or number from a query. This option seems logical, but does not work.

body, err := ioutil.ReadAll(r.Body)
if err != nil {
    return "", err
}

var id int

if err = json.Unmarshal(body, &id); err != nil {
    return "", err
}
return id, nil

You have to use an anonymous structure

body, err := ioutil.ReadAll(r.Body)
if err != nil {
    return "", err
}

id:= struct {
    Id int `json:"id"`
}{}

if err = json.Unmarshal(body, &id); err != nil {
    return "", err
}
return id.Id, nil

But every time I I use this option causes obvious hostility, it's clearly some kind of nonsense. Is there a normal way in Go to get a primitive from a body?

0 Answers
Related