6

Enable Cross Domain XMLHttpRequest Request in Go Server

 2 years ago
source link: https://siongui.github.io/2017/03/20/enable-cors-xhr-request-in-golang-server/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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).


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK