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
+12.7k Golang : Add ASCII art to command line application launching process
+19.4k Golang : How to count the number of repeated characters in a string?
+10.1k Golang : Identifying Golang HTTP client request
+5.8k Golang : Launching your executable inside a console under Linux
+7.9k Javascript : How to check a browser's Do Not Track status?
+12.7k Golang : Listen and Serve on sub domain example
+13.6k Golang : Query string with space symbol %20 in between
+13.5k Golang : Read XML elements data with xml.CharData example
+7.1k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+5.4k Unix/Linux : How to archive and compress entire directory ?
+22.2k Golang : Securing password with salt
+4.7k Fix Google Analytics Redundant Hostnames problem