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
+12k Golang : Convert(cast) uintptr to string example
+24.1k Golang : Storing cookies in http.CookieJar example
+10.8k Golang : Calculations using complex numbers example
+3.9k Mac OSX : Get disk partitions' size, type and name
+6.7k Golang : Convert source code to assembly language
+18k Golang : Get host name or domain name from IP address
+11.7k Golang : Exit, terminating or aborting a program
+4.6k Golang : Reclaim memory occupied by make() example
+16k Golang : Get number of CPU cores
+16.2k Golang : How to save log messages to file?
+11.6k Golang : Covert map/slice/array to JSON or XML format
+12.8k Golang : unknown escape sequence error