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.9k Python : Convert(cast) bytes to string example
+6.8k Nginx : Password protect a directory/folder
+3.3k Golang : Fix go-cron set time not working issue
+6.9k Golang : Levenshtein distance example
+7.2k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+11.6k Golang : Convert(cast) float to int
+8.9k Golang : How to capture return values from goroutines?
+15.2k Golang : Find location by IP address and display with Google Map
+4.5k Javascript : Detect when console is activated and do something about it
+29.8k Golang : Get time.Duration in year, month, week or day
+18.2k Golang : Get path name to current directory or folder
+11.2k Golang : Byte format example