Ad
Why Can't I Set Response Headers With Golang Net/http?
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
Related Questions
- → How to access the Visual interface for October?
- → How to implement DbDongle::convertTimestamps as workaround of invalid timestamps with MySql strict
- → Laravel 5: Apache php http authentication
- → Trait 'IlluminateFoundationBusDispatchesJobs' not found
- → Disable CSRF TokenMismatch for specific routes on Lumen
- → Change fill color of d3.js node
- → Authenticate with a cookie using laravel 5.1 and jwt
- → What is causing the web page to reload?
- → Is there any way to make an SVG object clickable?
- → Keeping uploaded files secure but still available via https
- → CORS missmatch because of http
- → 500 Internal Server Error Ajax Laravel
- → React: How to publish page on server using React-starter-kit
Ad