php editor Xigua This article will introduce how to use JSON format to return structure data in Go language. In HTTP requests, we usually need to return data to the client in the form of JSON. The Go language provides a simple and powerful way to achieve this requirement. By converting the structure data to JSON format and setting the correct response headers, we can easily return structured data to the client. This article will explain in detail how to use Go language to implement this function, and provide sample code to help readers better understand. Whether you are a beginner or an experienced developer, this article will provide you with valuable knowledge and tips. Let's get started now!
I have defined the following structure in go
:
type repostars struct { name string owner string stars int }
I created an array repoitems := []repostars{}
which contains multiple items of the above structure.
This is what repoitems
looks like:
I'm trying to return these items as a json response:
w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(repoItems)
And it looks empty
What am I doing wrong here?
If the structure field starts with a lowercase letter, it means is not exported. All unexported fields will not be serialized by the encoder.
Change the first letter to uppercase.
type repoStars struct { Name string Owner string Stars int }
The above is the detailed content of Go returns structs as JSON in HTTP requests. For more information, please follow other related articles on the PHP Chinese website!