Skip to content

Commit

Permalink
refactor(middleware): add CORS middleware and refactor HTTP service
Browse files Browse the repository at this point in the history
- 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
  • Loading branch information
pcfreak30 committed Sep 30, 2024
1 parent 8f9f2d1 commit 0bef280
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 9 deletions.
42 changes: 42 additions & 0 deletions middleware/cors.go
Original file line number Diff line number Diff line change
@@ -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
}
11 changes: 2 additions & 9 deletions service/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 0bef280

Please sign in to comment.