diff --git a/main.go b/main.go index 4a6b2c9..cb39d7c 100644 --- a/main.go +++ b/main.go @@ -2,18 +2,37 @@ package main import ( "context" - "go-rest-api/server" + "go-rest-api/handler" "log" + "net/http" "os" "os/signal" "time" + + "github.com/labstack/echo/v4" + "github.com/labstack/echo/v4/middleware" ) +var port = ":8000" + func main() { - s := server.NewServer(":8000") + e := echo.New() + e.Use(middleware.Logger()) + e.Use(middleware.Recover()) + e.Use(middleware.CORSWithConfig(middleware.CORSConfig{ + AllowOrigins: []string{"http://localhost:8000"}, + AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept}, + })) + + handler.AttachArticleHandlersToRouter(e) + + e.Static("/", "./public") + e.GET("/", defaultHandler) go func() { - s.Serve() + if err := e.Start(port); err != nil { + e.Logger.Info("Shutting down the server...") + } }() signCh := make(chan os.Signal) @@ -21,8 +40,15 @@ func main() { signal.Notify(signCh, os.Kill) sig := <-signCh - log.Println("Received terminal, graceful shutdown", sig) + log.Println("Received terminal, graceful shutdown.", sig) - tc, _ := context.WithTimeout(context.Background(), 30*time.Second) - s.Shutdown(tc) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := e.Shutdown(ctx); err != nil { + e.Logger.Fatal(err) + } +} + +func defaultHandler(c echo.Context) error { + return echo.NewHTTPError(http.StatusMethodNotAllowed, "Method not allowed.") } diff --git a/server/server.go b/server/server.go deleted file mode 100644 index 746cf02..0000000 --- a/server/server.go +++ /dev/null @@ -1,53 +0,0 @@ -package server - -import ( - "context" - "go-rest-api/handler" - "net/http" - - "github.com/labstack/echo/v4" - "github.com/labstack/echo/v4/middleware" -) - -// Server struct -type Server struct { - port string - server *http.Server -} - -// NewServer func -func NewServer(port string) Server { - return Server{ - server: &http.Server{ - Addr: port, - }, - } -} - -// Serve func -func (s *Server) Serve() { - e := echo.New() - - e.Use(middleware.Logger()) - e.Use(middleware.Recover()) - e.Use(middleware.CORSWithConfig(middleware.CORSConfig{ - AllowOrigins: []string{"http://localhost:8000"}, - AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept}, - })) - - handler.AttachArticleHandlersToRouter(e) - - e.Static("/", "./public") - e.GET("/", s.defaultHandler) - - e.Logger.Fatal(e.StartServer(s.server)) -} - -// Shutdown func -func (s *Server) Shutdown(tc context.Context) { - s.server.Shutdown(tc) -} - -func (s *Server) defaultHandler(c echo.Context) error { - return echo.NewHTTPError(http.StatusMethodNotAllowed, "Method not allowed.") -}