github.com/btccom/go-micro/v2@v2.9.3/api/server/cors/cors.go (about) 1 package cors 2 3 import ( 4 "net/http" 5 ) 6 7 // CombinedCORSHandler wraps a server and provides CORS headers 8 func CombinedCORSHandler(h http.Handler) http.Handler { 9 return corsHandler{h} 10 } 11 12 type corsHandler struct { 13 handler http.Handler 14 } 15 16 func (c corsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 17 SetHeaders(w, r) 18 19 if r.Method == "OPTIONS" { 20 return 21 } 22 23 c.handler.ServeHTTP(w, r) 24 } 25 26 // SetHeaders sets the CORS headers 27 func SetHeaders(w http.ResponseWriter, r *http.Request) { 28 set := func(w http.ResponseWriter, k, v string) { 29 if v := w.Header().Get(k); len(v) > 0 { 30 return 31 } 32 w.Header().Set(k, v) 33 } 34 35 if origin := r.Header.Get("Origin"); len(origin) > 0 { 36 set(w, "Access-Control-Allow-Origin", origin) 37 } else { 38 set(w, "Access-Control-Allow-Origin", "*") 39 } 40 41 set(w, "Access-Control-Allow-Credentials", "true") 42 set(w, "Access-Control-Allow-Methods", "POST, PATCH, GET, OPTIONS, PUT, DELETE") 43 set(w, "Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization") 44 }