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
+8.9k Golang : Read until certain character to break for loop
+9.4k Golang : Decompress zlib file example
+4.8k Golang : Calculate pivot points for a cross
+3.5k Swift : Convert (cast) Float to Int or Int32 value
+8.3k Golang : Generate random elements without repetition or duplicate
+10.8k Golang : Compress and decompress file with compress/flate example
+11.1k Golang : Convert IP version 6 address to integer or decimal number
+21.1k Find and replace a character in a string in Go
+6.3k Golang : Check if integer is power of four example
+15.6k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+14.4k Golang : Get number of CPU cores
+3k Golang : Valued expressions and functions example