Read the body of an api which is JSON

Hi i want to read the json body of a POST request
type MyData struct {
grant_type string json:"grant_type"
username string json:"username"
password string json:"password"

func main() {
http.HandleFunc("/", requestHandler)
log.Fatal(http.ListenAndServe(“”, nil))
func requestHandler(w http.ResponseWriter, r *http.Request) {

decoder := json.NewDecoder(r.Body)
var t MyData
err := decoder.Decode(&t)
if err != nil{

Expose the fields on the struct or JSON can’t see them.


Expanding on @NobbZ response, in your MyData type you need to make the fields start with capital letters like so:

type MyData struct {
  GrantType string json:"grant_type"
  Username string json:"username"
  Password string json:"password"

The encoding/json package will not fill in fields that are not exported.


json sent via post man
“grant_type”: “password”,
“username”: “m”,
“password”: “Password”

No, thats not what I meant.

What I meant was, that you need to expose the fields from the struct you want to marschall into/from.

The JSON (de)serializer wont be able to see and manipulate the fields if they are not exposed.

@joncalhoun explained pretty well how to do that.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.