Home  >  Article  >  Backend Development  >  How to send HTTP JSON request using Golang?

How to send HTTP JSON request using Golang?

WBOY
WBOYOriginal
2024-06-04 16:19:001003browse

How to use Go to send HTTP JSON request steps: Create http.Client object. Create an http.Request object, specifying the URL and method. Set the request header and set Content-Type to application/json. Encode JSON data into a byte array. Sets the byte array into the request body. Send the request and process the response.

如何使用 Golang 发送 HTTP JSON 请求?

How to send HTTP JSON request using Go

Introduction

Go language relies on Its rich HTTP library makes sending JSON requests very easy. This article will guide you how to use the net/http package to send HTTP JSON requests and provide a practical case.

Send a JSON request

Sending a JSON request requires the following steps:

  1. Create a http.Client object.
  2. Create a http.Request object and specify the URL and method to send the request.
  3. Set the request header and set Content-Type to application/json.
  4. Encode JSON data into a byte array.
  5. Set the byte array into the request body.
  6. Send the request and process the response.

Code example

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    // 创建数据
    data := map[string]string{"name": "Alice", "age": "25"}

    // 编码 JSON 数据
    jsonBytes, err := json.Marshal(data)
    if err != nil {
        fmt.Printf("Error encoding JSON: %v", err)
        return
    }

    // 创建请求
    req, err := http.NewRequest("POST", "http://example.com", bytes.NewReader(jsonBytes))
    if err != nil {
        fmt.Printf("Error creating request: %v", err)
        return
    }

    // 设置请求头
    req.Header.Set("Content-Type", "application/json")

    // 发送请求
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Printf("Error sending request: %v", err)
        return
    }

    // 读取响应
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Printf("Error reading response: %v", err)
        return
    }

    fmt.Println("Response:", string(body))
}

Practical case

This example sends a JSON request to the API to create a new User:

// 创建用户数据
type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

user := &User{Name: "Bob", Age: 30}

// 编码 JSON 数据
jsonBytes, err := json.Marshal(user)
// ...

// ... 使用上文中的其余代码发送请求 ...

The above is the detailed content of How to send HTTP JSON request using Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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