Home > Backend Development > Golang > How to get JSON data from server using REST API in Golang?

How to get JSON data from server using REST API in Golang?

WBOY
Release: 2024-06-01 11:51:56
Original
699 people have browsed it

Steps to obtain JSON data in Golang: Create an HTTP client; use HTTP requests to specify the request method, URL and request body; add HTTP headers; perform HTTP requests; check the response status code; parse the JSON response.

如何在 Golang 中使用 REST API 从服务器获取 JSON 数据?

How to use REST API in Golang to get JSON data from the server

In Golang, you can use the net/http package easily Get JSON data from REST API. Here's how to do it:

1. Create an HTTP client

You need to create a client for making HTTP requests.

// 创建一个新的 HTTP 客户端
client := &http.Client{}
Copy after login

2. Create HTTP request

Construct an HTTP request, specify the request method, URL and request body (if necessary).

// 创建一个新的 HTTP 请求
req, err := http.NewRequest(method, url, body)
if err != nil {
    fmt.Println(err)
    return
}
Copy after login

3. Add HTTP headers

You can add HTTP headers to the request as needed.

// 添加 HTTP 头
req.Header.Add("Content-Type", "application/json")
Copy after login

4. Perform HTTP requests

Use the client to perform HTTP requests.

// 执行 HTTP 请求
resp, err := client.Do(req)
if err != nil {
    fmt.Println(err)
    return
}
Copy after login

5. Check the response status code

Check the response status code to ensure the request was successful.

// 检查响应状态代码
if resp.StatusCode != http.StatusOK {
    fmt.Println("请求失败: ", resp.Status)
    return
}
Copy after login

6. Parse JSON response

Use the JSON decoder to decode the JSON response.

// 创建 JSON 解码器
decoder := json.NewDecoder(resp.Body)

// 解析 JSON 响应
var data interface{}
if err := decoder.Decode(&data); err != nil {
    fmt.Println(err)
    return
}
Copy after login

Practical case

Suppose you want to get user data from JSONPlaceholder API, you can use the following code:

func main() {
    // 创建 HTTP 请求
    resp, err := http.Get("https://jsonplaceholder.typicode.com/users")
    if err != nil {
        fmt.Println(err)
        return
    }

    // 检查状态代码
    if resp.StatusCode != 200 {
        fmt.Println(resp.Status)
        return
    }

    // 解析 JSON 响应
    var users []map[string]interface{}
    decoder := json.NewDecoder(resp.Body)
    if err := decoder.Decode(&users); err != nil {
        fmt.Println(err)
        return
    }

    // 打印用户名称
    for _, user := range users {
        fmt.Println(user["name"])
    }
}
Copy after login

This is how to get from the server using REST API in Golang Methods for JSON data.

The above is the detailed content of How to get JSON data from server using REST API in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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