Home > Backend Development > Golang > Let's talk about how to use JSON to make requests in Go language

Let's talk about how to use JSON to make requests in Go language

PHPz
Release: 2023-04-12 19:59:46
Original
1170 people have browsed it

In modern Web technology, JSON has become the mainstream data format. The json package in the Go language provides a series of functions and structures for JSON encoding and decoding, making using JSON very convenient. This article will introduce how to use JSON to make requests in the Go language.

The Go language provides many ways to send HTTP requests and process JSON responses. Here we introduce a common way:

Import the necessary packages

import (
    "encoding/json"
    "fmt"
    "net/http"
    "os"
)
Copy after login

Define the structure of the interface to be requested

type User struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
}
Copy after login

Send the request

func main() {
    url := "https://jsonplaceholder.typicode.com/users"    // 请求地址

    // 发送HTTP GET请求
    response, err := http.Get(url)
    if err != nil {
        fmt.Println("请求失败:", err)
        os.Exit(1)
    }
    defer response.Body.Close()

    // 将JSON响应解码到结构体
    var users []User
    err = json.NewDecoder(response.Body).Decode(&users)
    if err != nil {
        fmt.Println("解码失败:", err)
        os.Exit(1)
    }

    // 显示解码后的结构体
    for _, user := range users {
        fmt.Printf("姓名:%s,年龄:%d,邮箱:%s\n", user.Name, user.Age, user.Email)
    }
}
Copy after login

The above code will send an HTTP GET request to the specified URL and decode the response into a slice of User structure. You can modify it according to your needs.

To sum up, using JSON to make requests is a very common operation in Golang. Hope this article is helpful to you.

The above is the detailed content of Let's talk about how to use JSON to make requests in Go language. For more information, please follow other related articles on the PHP Chinese website!

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