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
+4.6k JQuery : Calling a function inside Jquery(document) block
+18.9k Golang : Get host name or domain name from IP address
+13.2k Facebook PHP getUser() returns 0
+5.6k Golang : List all packages and search for certain package
+16.5k Golang : Set up source IP address before making HTTP request
+20.2k Golang : Pipe output from one os.Exec(shell command) to another command
+7.9k Golang : Auto-generate reply email with text/template package
+4.4k Adding Skype actions such as call and chat into web page examples
+6.1k Golang : Detect face in uploaded photo like GPlus
+6.9k Golang : Transform lisp or spinal case to Pascal case example
+6.8k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+10.9k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example