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
+20.4k Golang : Use TLS version 1.2 and enforce server security configuration over client
+12.4k Golang : Reverse IP address for reverse DNS lookup example
+7.8k Golang : Get SPF and DMARC from email headers to fight spam
+11.7k Golang : Increment string example
+11.2k Golang : Remove or trim extra comma from CSV
+21k Golang : How to read JPG(JPEG), GIF and PNG files ?
+34.9k Golang : Display float in 2 decimal points and rounding up or down
+9.6k Golang : Create Temporary File
+5.5k Golang : Skip or discard items of non-interest when iterating example
+8.4k Golang : How to protect your source code from client, hosting company or hacker?
+35.5k Upload multiple files with Go
+9.2k JavaScript/JQuery : Detect or intercept enter key pressed example