gitee.com/sasukebo/go-micro/v4@v4.7.1/api/server/cors/cors.go (about) 1 package cors 2 3 import ( 4 "net/http" 5 ) 6 7 type Config struct { 8 AllowOrigin string 9 AllowCredentials bool 10 AllowMethods string 11 AllowHeaders string 12 } 13 14 // CombinedCORSHandler wraps a server and provides CORS headers 15 func CombinedCORSHandler(h http.Handler, config *Config) http.Handler { 16 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 17 if config != nil { 18 SetHeaders(w, r, config) 19 } 20 if r.Method == "OPTIONS" { 21 return 22 } 23 24 h.ServeHTTP(w, r) 25 }) 26 } 27 28 // SetHeaders sets the CORS headers 29 func SetHeaders(w http.ResponseWriter, _ *http.Request, config *Config) { 30 set := func(w http.ResponseWriter, k, v string) { 31 if v := w.Header().Get(k); len(v) > 0 { 32 return 33 } 34 w.Header().Set(k, v) 35 } 36 //For forward-compatible code, default values may not be provided in the future 37 if config.AllowCredentials { 38 set(w, "Access-Control-Allow-Credentials", "true") 39 } else { 40 set(w, "Access-Control-Allow-Credentials", "false") 41 } 42 if config.AllowOrigin == "" { 43 set(w, "Access-Control-Allow-Origin", "*") 44 } else { 45 set(w, "Access-Control-Allow-Origin", config.AllowOrigin) 46 } 47 if config.AllowMethods == "" { 48 set(w, "Access-Control-Allow-Methods", "POST, PATCH, GET, OPTIONS, PUT, DELETE") 49 } else { 50 set(w, "Access-Control-Allow-Methods", config.AllowMethods) 51 } 52 if config.AllowHeaders == "" { 53 set(w, "Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization") 54 } else { 55 set(w, "Access-Control-Allow-Headers", config.AllowHeaders) 56 } 57 }