How to Set HTTP Response Headers and Status Codes in Go

Web
Set HTTP status codes with WriteHeader and custom headers with Header.Set before writing the response body in Go.

Use w.WriteHeader() to set the status code and w.Header().Set() to add custom headers before writing the response body.

package main

import (
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("X-Custom-Header", "value")
	w.WriteHeader(http.StatusCreated)
	w.Write([]byte(`{"status": "ok"}`))
}

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