25% off

Use code FUNCMAIN at checkout for 25% off all premium courses.

Get started →
Making HTTP Requests with Custom Headers in Go
Code Snippet

Making HTTP Requests with Custom Headers in Go

go

When working with APIs, you often need to send custom headers for authentication, content negotiation, or other purposes. Go’s http.NewRequest function allows you to create a request object that you can customize before sending it. After creating the request, use the Header field to add custom headers with the Set method.

The http.Client type gives you control over request timeouts, redirects, and other options. By specifying a timeout, you ensure that requests don’t hang indefinitely. The Do method executes the request and returns the response, which contains the status code and response body.

Always remember to close the response body with defer resp.Body.Close() to free resources. If you need to read the response body, use io.ReadAll or read from the body reader directly. This pattern is essential for working with REST APIs and other HTTP-based services.

Further Reading: