When developing a web server in Go, occasionally it may become necessary to set HTTP headers on requests. This is where the gorilla/mux and net/http libraries prove useful.
Setting Response Headers
To set an HTTP header on a response, simply use the Set() method of the Header() method on the ResponseWriter:
func saveHandler(w http.ResponseWriter, r *http.Request) { // allow cross domain AJAX requests w.Header().Set("Access-Control-Allow-Origin", "*") // ... }
Example Usage
In this example, we set the "Access-Control-Allow-Origin" header to "*", allowing cross-domain AJAX requests.
Gotchas
Ensure your saveHandler function includes the necessary import at the top:
import ( "net/http" )
The above is the detailed content of How Do I Set HTTP Headers in Go?. For more information, please follow other related articles on the PHP Chinese website!