Setting Headers in a Go HTTP Server
When developing web APIs, it's often necessary to set HTTP headers on response objects to control the behavior of the browser. In Go, using gorilla/mux and net/http to build a web server, setting response headers is a straightforward process.
Consider this example, which aims to allow cross-domain AJAX requests by setting the "Access-Control-Allow-Origin" header to "*":
package main import ( "net/http" "github.com/gorilla/mux" ) func saveHandler(w http.ResponseWriter, r *http.Request) { // allow cross domain AJAX requests w.Header().Set("Access-Control-Allow-Origin", "*") } func main() { r := mux.NewRouter() r.HandleFunc("/save", saveHandler) http.Handle("/", r) http.ListenAndServe(":"+port, nil) }
The key to setting response headers is the Header() method on the ResponseWriter object:
In this case, the code uses w.Header().Set("Access-Control-Allow-Origin", "*") to add the desired header and value. The result will be an HTTP response with the "Access-Control-Allow-Origin" header set to "*".
This simple method allows you to control the HTTP headers sent with your server's responses, enabling features such as Cross-Origin Resource Sharing (CORS).
The above is the detailed content of How to Set HTTP Response Headers in a Go Web Server using gorilla/mux?. For more information, please follow other related articles on the PHP Chinese website!