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

Go returns structs as JSON in HTTP requests

WBOY
Release: 2024-02-09 14:10:21
forward
991 people have browsed it

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
}
Copy after login

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)
Copy after login

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
}
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template