Home > Backend Development > Golang > How to Customize HTTP GET Request Headers in Go?

How to Customize HTTP GET Request Headers in Go?

Patricia Arquette
Release: 2025-01-02 14:16:39
Original
239 people have browsed it

How to Customize HTTP GET Request Headers in Go?

Customizing Request Headers in HTTP GET Requests in Go

In Go, when performing an HTTP GET request using the standard library's http package, it is possible to set custom headers for the request. Here's how you can do this:

The http package provides a Header field in the Request struct, which allows you to add, modify, and retrieve headers associated with the request. To set a header, you can use the Set method, as shown in the example below:

client := &http.Client{}
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("name", "value")
res, _ := client.Do(req)
Copy after login

In this example, a custom header named "name" is set to the value "value." The request is then executed using the Do method of the http.Client.

You can set multiple headers by repeatedly using the Set method. For instance, the following code sets two headers:

req.Header.Set("name", "value")
req.Header.Set("another-header", "another-value")
Copy after login

The Header field is a map of string keys and string values. You can use the Get method to retrieve the value of an existing header:

value := req.Header.Get("name")
Copy after login

To remove a header, you can use the Del method:

req.Header.Del("name")
Copy after login

The above is the detailed content of How to Customize HTTP GET Request Headers in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template