HTTP Headers With Go

HTTP Headers With Go

I was looking how to add HTTP headers to the HTTP responses and here it is how:

package main

import (
	"fmt"
	"net/http"
)

func handlerFunc(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.Header().Add("Fake", "my fake header")
	w.Header().Set("Content-Type", "text/plain")

	// w.WriteHeader(20000)
	fmt.Fprint(w, "<h1> Welcome to my site </h1>")
}

func main() {

	http.HandleFunc("/", handlerFunc)
	fmt.Println("Starting the server on :3000...")
	http.ListenAndServe(":3000", nil)

}

The one doing the magic is the Header() method. The previous example shows to possible actions:

Add: Add adds the key, value pair to the header. It appends to any existing values associated with key.

Set: Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key.


For further info, please check Go Documentation:

https://pkg.go.dev/net/http#Header

 Share!

 
comments powered by Disqus