Enable Cross Domain XMLHttpRequest Request in Go Server
Howto
To enable cross-domain XHR requests in servers, we need to set the following header in request response:
Access-Control-Allow-Origin: *
The above header says all requests from any other domain are allowed.
To set the Access-Control-Allow-Origin header in Go server via standard net/http package, we can use the following code in request handler:
func myHandler(w http.ResponseWriter, r *http.Request) {
// allow all XHR requests from other domains
w.Header().Set("Access-Control-Allow-Origin", "*")
}
Just one line of code to make your Go server enable Cross-Origin Resource Sharing (CORS).
Complete Example
The following is complete sample code for servers supporting CORS and running on Google App Engine Go Standard Environment
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package servejson import ( "fmt" "net/http" ) func init() { http.HandleFunc("/", servejson) } func servejson(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") fmt.Fprint(w, `{"a":"b","c":"d"}`) } |
1 2 3 4 5 6 | runtime: go api_version: go1 handlers: - url: /.* script: _go_app |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | export PATH := $(PATH):$(realpath ../../../../../go_appengine/) PROJECT_DIR=$(CURDIR) PROJECT_ID=golden-operator-130720 PROJECT_VERSION=blogexample default: @echo "\033[92mRun development web server ...\033[0m" @goapp serve fmt: @echo "\033[92mGo fmt source code ...\033[0m" @goapp fmt *.go deploy: goapp deploy -application ${PROJECT_ID} -version ${PROJECT_VERSION} ${PROJECT_DIR} @echo "\033[92mDeployed URL: http://${PROJECT_VERSION}.${PROJECT_ID}.appspot.com/\033[0m" |
Tested on:
- Google App Engine Go 1.6
References:
[1] |
[2] | Setting HTTP headers in Golang - Stack Overflow |
[3] | Load balancer at your fingertips, let's build one (Go) : golang |