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
+26.6k Golang : Validate email address with regular expression
+8.3k Golang : Qt progress dialog example
+2.1k Golang : Experimental Jawi programming language
+4.8k Golang : Hue, Saturation and Value(HSV) with OpenCV example
+8k Golang : How to check if your program is running in a terminal
+5.8k Golang : Gorilla web tool kit schema example
+8.7k Golang : Pass database connection to function called from another package and HTTP Handler
+3.6k Golang : How to verify input is rune?
+4.5k How to let Facebook Login button redirect to a particular URL ?
+16.4k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
+3.4k Golang : Use NLP to get sentences for each paragraph example
+7.7k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example