diff --git a/pkg/api/router.go b/pkg/api/router.go index 5c8d059..34eaecc 100644 --- a/pkg/api/router.go +++ b/pkg/api/router.go @@ -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) diff --git a/pkg/middleware/cors.go b/pkg/middleware/cors.go new file mode 100644 index 0000000..afde166 --- /dev/null +++ b/pkg/middleware/cors.go @@ -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 + }) +}