feat(api): add basic CORS support

This commit is contained in:
Nicolas Carlier 2019-01-03 15:57:14 +00:00
parent 4d2c75e70b
commit 7a6af7312a
2 changed files with 20 additions and 0 deletions

View File

@ -23,6 +23,7 @@ func NewRouter(conf *config.Config) *http.ServeMux {
var handler http.Handler
handler = route.HandlerFunc(conf)
handler = middleware.Cors(handler)
handler = middleware.Logger(handler)
handler = middleware.Tracing(nextRequestID)(handler)

19
pkg/middleware/cors.go Normal file
View File

@ -0,0 +1,19 @@
package middleware
import (
"net/http"
)
// Cors is a middleware to enabling CORS on HTTP requests
func Cors(inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization")
if r.Method != "OPTIONS" {
inner.ServeHTTP(w, r)
}
return
})
}