Go return struct as JSON in HTTP request

Advertisements

I’ve defined the following struct in Go:

type repoStars struct {
name string
owner string
stars int
}

And I’ve created an array repoItems := []repoStars{} which has multiple items of the struct above.

This is how repoItems looks like:

I’m trying to return those items as a JSON response:

    w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(repoItems)

And it seems empty

What am I doing wrong here?

>Solution :

If the struct fields start with a lower case letter it means unexported. All unexported fields won’t be serialised by the encoder.

Change it to capital first letter.

type repoStars struct {
    Name string
    Owner string
    Stars int
}

Leave a Reply Cancel reply