How to set HTTP request header? 1. Use the http.Header type, where the key is the header field name and the value is the header field value; 2. Use the Set() method to set a single header, and the Add() method to set multiple headers; 3. Get the header through the Get() method, Delete the header via the Del() method.
How to set HTTP request headers in Golang
Setting HTTP request headers in Go is very simple, just use http.Header
type. http.Header
is a key-value map, where the key is the header field name and the value is the header field value.
To set a single header, you can use the Set
method:
import ( "net/http" "fmt" ) func main() { req, err := http.NewRequest("GET", "http://example.com", nil) if err != nil { // 处理错误 } req.Header.Set("Content-Type", "application/json") }
To set multiple To get the header, you can use the Add
method:
func main() { req, err := http.NewRequest("GET", "http://example.com", nil) if err != nil { // 处理错误 } req.Header.Add("Content-Type", "application/json") req.Header.Add("Accept", "application/json") }
To get the header, you can use the Get
method:
func main() { req, err := http.NewRequest("GET", "http://example.com", nil) if err != nil { // 处理错误 } contentType := req.Header.Get("Content-Type") fmt.Println(contentType) // "application/json" }
To delete the header, you can use the Del
method:
func main() { req, err := http.NewRequest("GET", "http://example.com", nil) if err != nil { // 处理错误 } req.Header.Del("Content-Type") }
The following is a complete practical case to demonstrate how to set up, Get and delete HTTP request headers:
package main import ( "fmt" "net/http" ) func main() { // 创建一个新的请求 req, err := http.NewRequest("GET", "http://example.com", nil) if err != nil { // 处理错误 } // 设置一个头 req.Header.Set("Content-Type", "application/json") // 获取一个头 contentType := req.Header.Get("Content-Type") fmt.Println(contentType) // "application/json" // 删除一个头 req.Header.Del("Content-Type") }
The above is the detailed content of How to set HTTP request headers in Golang?. For more information, please follow other related articles on the PHP Chinese website!