How to Set or Get HTTP Headers in Golang Server

Robin
Updated on December 1, 2023

If you are using the http package to set up your Go server, you can easily set and get HTTP headers inside your route handlers.

Golang provides a built-in Set() method to set headers to the response and the Get() method to get headers from the incoming request.

Set Response Headers in Go

Inside your route handler function, you have access to the w (http.ResponseWriter) parameter which has the Header() method.

First, call the Header() method and then call the Set() method on it to set individual headers.

          package main

import (
	"fmt"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	// Set headers
	w.Header().Set("Content-Type", "text/plain")
	w.Header().Set("Custom-Header", "Hello")

	fmt.Fprintf(w, "Hello, this is the response body!")
}

func main() {
	// Define a handler function
	http.HandleFunc("/", handler)

	// Start the HTTP server on port 8080
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println("Error starting server:", err)
	}
}

        

The Set() method accepts 2 parameters. The first parameter is the name of the header and the second parameter is the value.

In the example, I am setting two headers: "Content-Type" to "text/plain" and a custom header "Custom-Header" to "Hello". You can customize these headers according to your requirements.

There is a Add() method that also can add values to your headers. But Set() and Add() methods work differently.


Set() Method

When you set a header using the Set() method it will overwrite the previous values of that header.

          w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Content-Type", "charset=utf") // This value will replace the previous value

// The value of "Content-Type" header will be "charset=utf"

        

If I call the Set() method 2 times with the same header in this case "Content-Type", the second value will replace the first one.

The final value of the "Content-Type" header will be "charset=utf".


Add() Method

The Add() method will add a new value to a header field without replacing existing values.

This is particularly useful when you manipulate headers that can have multiple values.

          // Add multiple values for the "Set-Cookie" header
w.Header().Add("Set-Cookie", "user=John")
w.Header().Add("Set-Cookie", "sessionID=12345")

// The "Set-Cookie" header will contain both values ("user=John" and "sessionID=12345").
        

Here I am calling the Add() method to add two values ("user=John" and "sessionID=12345") for the "Set-Cookie" header.

Also Read: How to Set and Get Cookies in Golang Server

If this header already has values, this method will append to the existing ones.

Note: Header name is case-insensitive. For example, both methods will treat "Content-Type" and "content-type" as equivalent.


Get Request Headers in Go

To get header values from the request, call the r.Header.Get() method from *http.Request inside your route handler.

This method takes only one parameter which is the name of the header.

          package main

import (
	"fmt"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
        // Accessing request headers
        auth := r.Header.Get("Authorization")

        // Add your logic here

	fmt.Fprintf(w, "Hello, this is the response body!")
}

func main() {
	// Define a handler function
	http.HandleFunc("/", handler)

	// Start the HTTP server on port 8080
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println("Error starting server:", err)
	}
}

        

Here I call calling the Get() method to get the value of the "Authorization" header. It will return the value as a string.

If there is no value for the header, it will return an empty string ("").

Note: Header name in this method is case-insensitive. For example, "Authorization" and "authorization" are the same.

Related Posts