Removed useless Server struct
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Piotr Biernat 2020-09-26 23:27:30 +02:00
parent e1019a5ecc
commit f30344c658
2 changed files with 32 additions and 59 deletions

38
main.go
View File

@ -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.")
}

View File

@ -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.")
}