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
+18.3k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+18.2k Golang : Convert seconds to human readable time format example
+5.8k CloudFlare : Another way to get visitor's real IP address
+50.4k Golang : How to get struct field and value by name
+4.3k Golang : How to deal with configuration data?
+12k Golang : Linear algebra and matrix calculation example
+4.5k Golang : Shortening import identifier
+13k Golang : Send email with attachment(RFC2822) using Gmail API example
+18.4k Swift : Convert (cast) Int to int32 or Uint32
+13.5k Golang : Execute function at intervals or after some delay
+13.1k Golang : How to determine if user agent is a mobile device example
+10.3k Golang : GTK Input dialog box examples