Ad

Why Can't I Set Response Headers With Golang Net/http?

- 1 answer

With a simple HTTP server in Go, whether I use Add() or Set()...

package main
import "net/http"
func main() {
        http.HandleFunc("/", respond)
        http.ListenAndServe(":8888", nil)
}
func respond(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(200)
        w.Header().Add("Content-Type", "text/css")
        w.Header().Set("Access-Control-Allow-Origin", "*")
        w.Write([]byte("Hello!"))
}

...my headers are not added!

$ curl -IX GET localhost:8888
HTTP/1.1 200 OK
Date: Tue, 01 Feb 2022 00:24:53 GMT
Content-Length: 6
Content-Type: text/plain; charset=utf-8

Is there something I'm doing wrong? What's the proper way to add response headers?

Ad

Answer

You have to set the headers before writing the header:

w.Header().Add("Content-Type", "text/css")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.WriteHeader(200)
w.Write([]byte("Hello!"))
Ad
source: stackoverflow.com
Ad