diff --git a/src/router/api.go b/src/router/api.go index 3c42a98..897fb14 100644 --- a/src/router/api.go +++ b/src/router/api.go @@ -12,8 +12,8 @@ import ( "github.com/kevinanielsen/go-fast-cdn/src/util" ) -func AddApiRoutes(r *gin.Engine) { - api := r.Group("/api") +func (s *Server) AddApiRoutes() { + api := s.Engine.Group("/api") api.GET("/", func(c *gin.Context) { c.JSON(http.StatusOK, "pong") }) diff --git a/src/router/router.go b/src/router/router.go index cf7dd29..cd0858d 100644 --- a/src/router/router.go +++ b/src/router/router.go @@ -3,7 +3,6 @@ package router import ( "os" - "github.com/gin-gonic/gin" "github.com/kevinanielsen/go-fast-cdn/src/middleware" "github.com/kevinanielsen/go-fast-cdn/ui" ) @@ -11,15 +10,18 @@ import ( // Router initializes the router and sets up middleware, routes, etc. // It returns a *gin.Engine instance configured with the routes, middleware, etc. func Router() { - r := gin.Default() + port := ":" + os.Getenv("PORT") - r.Use(middleware.CORSMiddleware()) + s := NewServer( + WithPort(port), + WithMiddleware(middleware.CORSMiddleware()), + ) // Add all the API routes - AddApiRoutes(r) + s.AddApiRoutes() // Add the embedded ui routes - ui.AddRoutes(r) + ui.AddRoutes(s.Engine) - r.Run(":" + os.Getenv("PORT")) + s.Run() } diff --git a/src/router/server.go b/src/router/server.go new file mode 100644 index 0000000..4a79689 --- /dev/null +++ b/src/router/server.go @@ -0,0 +1,37 @@ +package router + +import "github.com/gin-gonic/gin" + +type Server struct { + Engine *gin.Engine + Port string +} + +func NewServer(options ...func(s *Server)) *Server { + s := &Server{ + Engine: gin.Default(), + Port: ":8080", + } + + for _, option := range options { + option(s) + } + + return s +} + +func WithPort(port string) func(*Server) { + return func(s *Server) { + s.Port = port + } +} + +func WithMiddleware(middleware gin.HandlerFunc) func(*Server) { + return func(s *Server) { + s.Engine.Use(middleware) + } +} + +func (s *Server) Run() { + s.Engine.Run(s.Port) +}