Implement api/server/cors (#1294)

This commit is contained in:
ben-toogood 2020-03-04 11:40:53 +00:00 committed by GitHub
parent 6a9001bdb1
commit 6d803d9e45
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 58 additions and 1 deletions

43
api/server/cors/cors.go Normal file
View File

@ -0,0 +1,43 @@
package cors
import (
"net/http"
)
// CombinedCORSHandler wraps a server and provides CORS headers
func CombinedCORSHandler(h http.Handler) http.Handler {
return corsHandler{h}
}
type corsHandler struct {
handler http.Handler
}
func (c corsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
SetHeaders(w, r)
if r.Method == "OPTIONS" {
return
}
c.handler.ServeHTTP(w, r)
}
// SetHeaders sets the CORS headers
func SetHeaders(w http.ResponseWriter, r *http.Request) {
set := func(w http.ResponseWriter, k, v string) {
if v := w.Header().Get(k); len(v) > 0 {
return
}
w.Header().Set(k, v)
}
if origin := r.Header.Get("Origin"); len(origin) > 0 {
set(w, "Access-Control-Allow-Origin", origin)
} else {
set(w, "Access-Control-Allow-Origin", "*")
}
set(w, "Access-Control-Allow-Methods", "POST, PATCH, GET, OPTIONS, PUT, DELETE")
set(w, "Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}

View File

@ -10,6 +10,7 @@ import (
"github.com/gorilla/handlers" "github.com/gorilla/handlers"
"github.com/micro/go-micro/v2/api/server" "github.com/micro/go-micro/v2/api/server"
"github.com/micro/go-micro/v2/api/server/cors"
log "github.com/micro/go-micro/v2/logger" log "github.com/micro/go-micro/v2/logger"
) )
@ -45,7 +46,13 @@ func (s *httpServer) Init(opts ...server.Option) error {
} }
func (s *httpServer) Handle(path string, handler http.Handler) { func (s *httpServer) Handle(path string, handler http.Handler) {
s.mux.Handle(path, handlers.CombinedLoggingHandler(os.Stdout, handler)) h := handlers.CombinedLoggingHandler(os.Stdout, handler)
if s.opts.EnableCORS {
h = cors.CombinedCORSHandler(h)
}
s.mux.Handle(path, h)
} }
func (s *httpServer) Start() error { func (s *httpServer) Start() error {

View File

@ -10,12 +10,19 @@ type Option func(o *Options)
type Options struct { type Options struct {
EnableACME bool EnableACME bool
EnableCORS bool
ACMEProvider acme.Provider ACMEProvider acme.Provider
EnableTLS bool EnableTLS bool
ACMEHosts []string ACMEHosts []string
TLSConfig *tls.Config TLSConfig *tls.Config
} }
func EnableCORS(b bool) Option {
return func(o *Options) {
o.EnableCORS = b
}
}
func EnableACME(b bool) Option { func EnableACME(b bool) Option {
return func(o *Options) { return func(o *Options) {
o.EnableACME = b o.EnableACME = b