Golang : How to Set or Add Header http.ResponseWriter?
Problem :
How to set or add header to http.ResponseWriter?
Solution :
The solution is similar to previous tutorial on how to set or add header to HTTP Request. All you need to do is to use the Add() or Set() methods in the http.ResponseWriter.Header() function. (http://golang.org/pkg/net/http/#ResponseWriter)
For example :
package main
import (
"net/http"
"strings"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func ReplyName(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*") //<---------- here!
URISegments := strings.Split(r.URL.Path, "/")
w.Write([]byte(URISegments[1]))
}
func main() {
// http.Handler
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
mux.HandleFunc("/replyname", ReplyName)
http.ListenAndServe(":8080", mux)
}
See also : Golang : Set or Add HTTP Request Headers
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.2k Golang : Find the length of big.Int variable example
+5.6k Unix/Linux : Get reboot history or check when was the last reboot date
+5.2k Golang : Intercept, inject and replay HTTP traffics from web server
+6.3k Golang : Calculate diameter, circumference, area, sphere surface and volume
+25.6k Golang : How to read integer value from standard input ?
+5k Golang : The Tao of importing package
+27.2k Golang : dial tcp: too many colons in address
+28.5k Golang : Detect (OS) Operating System
+20.5k Golang : Saving private and public key to files
+5.2k Javascript : How to loop over and parse JSON data?
+5.6k Golang : Error handling methods
+4.6k Which content-type(MIME type) to use for JSON data