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
+16.8k Golang : Delete files by extension
+13.2k Golang : List objects in AWS S3 bucket
+30.6k Get client IP Address in Go
+23.6k Golang : Check if element exist in map
+5.6k Golang *File points to a file or directory ?
+9.3k Golang : How to capture return values from goroutines?
+15.5k nginx: [emerg] unknown directive "ssl"
+21.4k Golang : How to get time zone and load different time zone?
+13k Golang : Convert IPv4 address to packed 32-bit binary format
+5.4k Golang : Customize scanner.Scanner to treat dash as part of identifier
+6.2k Golang : Function as an argument type example
+7.5k Golang : Calculate how many weeks left to go in a given year