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.
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:
http.Client
object. http.Request
object and specify the URL and method to send the request. Content-Type
to application/json
. 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!