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
+10.3k Golang : Get local time and equivalent time in different time zone
+6.2k Golang : Handling image beyond OpenCV video capture boundary
+12k Golang : Print UTF-8 fonts on image example
+15.7k Golang : Read a file line by line
+9.2k Golang : Changing a RGBA image number of channels with OpenCV
+5.1k Swift : Convert string array to array example
+9k Golang : Generate random Chinese, Japanese, Korean and other runes
+15.2k Golang : Force download file example
+5.1k Responsive Google Adsense
+7.6k Golang : Generate human readable password
+21.5k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+10k Golang : How to profile or log time spend on execution?