如何设置 http 请求头?1. 使用 http.header 类型,其中键是头字段名称,值是头字段值;2. 使用 set() 方法设置单个头,add() 方法设置多个头;3. 通过 get() 方法获取头,通过 del() 方法删除头。
如何在 Golang 中设置 HTTP 请求头
在 Go 中设置 HTTP 请求头非常简单,只需使用 http.Header 类型即可。http.Header 是一个键值对映射,其中键是头字段名称,值是头字段值。
设置单个头
要设置单个头,可以使用 Set 方法:
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") }
登录后复制
设置多个头
要设置多个头,可以使用 Add 方法:
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") }
登录后复制
获取头
要获取头,可以使用 Get 方法:
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" }
登录后复制
删除头
要删除头,可以使用 Del 方法:
func main() { req, err := http.NewRequest("GET", "http://example.com", nil) if err != nil { // 处理错误 } req.Header.Del("Content-Type") }
登录后复制
实战案例
以下是一个完整的实战案例,演示如何设置、获取和删除 HTTP 请求头:
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") }
登录后复制
以上就是在 Golang 中如何设置 HTTP 请求头?的详细内容,更多请关注叮当号网其它相关文章!
文章来自互联网,只做分享使用。发布者:老板不要肥肉,转转请注明出处:https://www.dingdanghao.com/article/494884.html