From 0bef28089f13bb5a82aa8dc1bde90bdd41dbff29 Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Mon, 30 Sep 2024 04:00:16 -0400 Subject: [PATCH] refactor(middleware): add CORS middleware and refactor HTTP service - Add new CorsMiddleware function in middleware/cors.go - Implement default CORS options with customization support - Replace direct usage of rs/cors in service/http.go with new middleware - Update HTTP service to use the new CorsMiddleware --- middleware/cors.go | 42 ++++++++++++++++++++++++++++++++++++++++++ service/http.go | 11 ++--------- 2 files changed, 44 insertions(+), 9 deletions(-) create mode 100644 middleware/cors.go diff --git a/middleware/cors.go b/middleware/cors.go new file mode 100644 index 00000000..108ed36d --- /dev/null +++ b/middleware/cors.go @@ -0,0 +1,42 @@ +package middleware + +import ( + "github.com/rs/cors" + "net/http" +) + +var defaultCorsOptions = cors.Options{ + AllowOriginFunc: func(origin string) bool { + return true + }, + AllowedMethods: []string{"GET", "POST", "PATCH", "DELETE", "HEAD", "OPTIONS"}, + AllowedHeaders: []string{"*"}, + AllowCredentials: true, +} + +func CorsMiddleware(opts *cors.Options) func(h http.Handler) http.Handler { + mergedOpts := defaultCorsOptions + + if opts != nil { + if opts.AllowOriginFunc != nil { + mergedOpts.AllowOriginFunc = opts.AllowOriginFunc + } + if len(opts.AllowedMethods) > 0 { + mergedOpts.AllowedMethods = opts.AllowedMethods + } + if len(opts.AllowedHeaders) > 0 { + mergedOpts.AllowedHeaders = opts.AllowedHeaders + } + if len(opts.ExposedHeaders) > 0 { + mergedOpts.ExposedHeaders = opts.ExposedHeaders + } + if opts.AllowCredentials != mergedOpts.AllowCredentials { + mergedOpts.AllowCredentials = opts.AllowCredentials + } + if opts.MaxAge > 0 { + mergedOpts.MaxAge = opts.MaxAge + } + } + + return cors.New(mergedOpts).Handler +} diff --git a/service/http.go b/service/http.go index 26b0da65..fc8c64d4 100644 --- a/service/http.go +++ b/service/http.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/gorilla/handlers" "github.com/gorilla/mux" - "github.com/rs/cors" "go.lumeweb.com/httputil" "go.lumeweb.com/portal/core" "go.lumeweb.com/portal/middleware" @@ -95,16 +94,10 @@ func (h *HTTPServiceDefault) Init() error { h.Router().PathPrefix("/debug/").Handler(http.DefaultServeMux).Use(authMw) - corsOpts := cors.Options{ - AllowedOrigins: []string{"*"}, - AllowedMethods: []string{"GET"}, - AllowedHeaders: []string{"Authorization", "Content-Type"}, - AllowCredentials: true, - } - corsHandler := cors.New(corsOpts) + corsHandler := middleware.CorsMiddleware(nil) rootApi := h.Router().PathPrefix("/api").Subrouter() - rootApi.Use(corsHandler.Handler) + rootApi.Use(corsHandler) rootApi.HandleFunc("/meta", h.apiMetaHandler).Methods(http.MethodGet) return nil