Add CORS support

This commit is contained in:
Ivan Danyliuk 2018-09-19 20:50:26 +03:00
parent 2e30599707
commit 01d186ae2c
No known key found for this signature in database
GPG Key ID: 97ED33CE024E1DBF
2 changed files with 21 additions and 1 deletions

View File

@ -0,0 +1,20 @@
package main
import "net/http"
func allowCORS(fn func(w http.ResponseWriter, r *http.Request)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Access-Control-Allow-Origin"); origin == "" {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
w.Header().Set("Access-Control-Allow-Headers", "*")
if origin := r.Header.Get("Origin"); origin != "" {
if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" {
// set preflight options
return
}
}
fn(w, r)
}
}

View File

@ -25,7 +25,7 @@ func main() {
if *server {
log.Println("Starting simulator server on", *serverAddr)
http.HandleFunc("/", simulationHandler)
http.HandleFunc("/", allowCORS(simulationHandler))
log.Fatal(http.ListenAndServe(*serverAddr, nil))
return
}