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
+6.3k Golang : Getting Echo framework StartAutoTLS to work
+14.2k Golang : How to add color to string?
+24.5k Golang : How to write CSV data to file
+5.7k PHP : Shuffle to display different content or advertisement
+7k Golang : Get final or effective URL with Request.URL example
+6.5k Golang : Command line ticker to show work in progress
+5.7k Golang : Warp text string by number of characters or runes example
+9.5k Golang : How to transmit update file to client by HTTP request example
+12.7k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+16.1k Golang : How to make a file read only and set it to writable again?
+7.3k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+12.1k Golang : Convert(cast) int to int64