Home  >  Article  >  Backend Development  >  Go returns structs as JSON in HTTP requests

Go returns structs as JSON in HTTP requests

WBOY
WBOYforward
2024-02-09 14:10:21952browse

Go 在 HTTP 请求中以 JSON 形式返回结构体

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!

Question content

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?

Solution

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete