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
+12.6k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+39.6k Golang : How to check if a string contains another sub-string?
+16.3k Golang : Aligning strings to right, left and center with fill example
+22.7k Golang : How to validate URL the right way
+4.3k Golang : How to deal with configuration data?
+19.2k Golang : Convert date string to variants of time.Time type examples
+4.1k Swift : Convert (cast) Float to Int or Int32 value
+7.2k Swift : Convert (cast) Character to Integer?
+4.8k Golang : Denco multiplexer example
+5.3k CodeIgniter : form input set_value cause " to become & quot
+23.3k Golang : convert rune to integer value
+5.6k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?