Skip to content

Commit

Permalink
refactor: integrate middleware package into server/rest
Browse files Browse the repository at this point in the history
  • Loading branch information
turtleDev committed Sep 9, 2024
1 parent c32b74d commit 939727d
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 49 deletions.
2 changes: 0 additions & 2 deletions cmd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"github.com/raystack/raccoon/config"
"github.com/raystack/raccoon/pkg/logger"
"github.com/raystack/raccoon/pkg/metrics"
"github.com/raystack/raccoon/pkg/middleware"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
Expand All @@ -24,7 +23,6 @@ func serverCommand() *cobra.Command {
if err != nil {
return err
}
middleware.Load()
metrics.Setup()
defer metrics.Close()
logger.SetLevel(config.Log.Level)
Expand Down
31 changes: 0 additions & 31 deletions pkg/middleware/cors.go

This file was deleted.

11 changes: 0 additions & 11 deletions pkg/middleware/util.go

This file was deleted.

21 changes: 16 additions & 5 deletions server/rest/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import (
"net/http"
"time"

"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/raystack/raccoon/config"
"github.com/raystack/raccoon/core/collector"
"github.com/raystack/raccoon/pkg/metrics"
"github.com/raystack/raccoon/pkg/middleware"
"github.com/raystack/raccoon/server/rest/websocket"
"github.com/raystack/raccoon/server/rest/websocket/connection"
)
Expand Down Expand Up @@ -38,7 +38,7 @@ func NewRestService(c collector.Collector) *Service {
subRouter.HandleFunc("/events", restHandler.RESTAPIHandler).Methods(http.MethodPost).Name("events")

server := &http.Server{
Handler: applyMiddleware(router),
Handler: withCORS(router),
Addr: ":" + config.Server.Websocket.AppPort,
}
return &Service{
Expand All @@ -47,9 +47,20 @@ func NewRestService(c collector.Collector) *Service {
}
}

func applyMiddleware(router http.Handler) http.Handler {
h := middleware.GetCors()(router)
return h
func withCORS(router http.Handler) http.Handler {
if !config.Server.CORS.Enabled {
return router
}
opts := []handlers.CORSOption{handlers.AllowedHeaders(config.Server.CORS.AllowedHeaders),
handlers.AllowedMethods(config.Server.CORS.AllowedMethods),
handlers.AllowedOrigins(config.Server.CORS.AllowedOrigin)}
if config.Server.CORS.AllowCredentials {
opts = append(opts, handlers.AllowCredentials())
}
if config.Server.CORS.MaxAge > 0 {
opts = append(opts, handlers.MaxAge(config.Server.CORS.MaxAge))
}
return handlers.CORS(opts...)(router)
}

func pingHandler(w http.ResponseWriter, r *http.Request) {
Expand Down

0 comments on commit 939727d

Please sign in to comment.