Home  >  Article  >  Backend Development  >  How to set HTTP request headers in Golang?

How to set HTTP request headers in Golang?

WBOY
WBOYOriginal
2024-06-04 20:00:59750browse

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.

在 Golang 中如何设置 HTTP 请求头?

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.

Set a single header

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")
}

Set multiple headers

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")
}

Get the header

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"
}

Delete the header

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")
}

Practical case

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!

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