Skip to content

Set Header to Response in Golang (HTTP Handler)

On the response writer variable call the Header() method and then Set() to set the header you want to add:

w.Header().Set("Content-Type", "text/plain")

This snippet is complete and help you to check how it works:

package main

import (
	"fmt"
	"net/http"
	"time"
)

func greetHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	w.Header().Set("Access-Control-Allow-Origin", "*")

	w.WriteHeader(http.StatusOK)

	fmt.Fprintf(w, "Hello World! %s", time.Now())
}

func main() {
	http.HandleFunc("/", greetHandler)
	http.ListenAndServe(":8080", nil)
}

Leave a Reply

Your email address will not be published. Required fields are marked *