rest-api/main.go

57 lines
1.2 KiB
Go

package main
import (
"context"
"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() {
// framework setup
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"http://localhost:8000"}, // FIXME use env var or sth like that
AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
}))
handler.AttachArticleHandlersToRouter(e)
handler.AttachProductHandlersToRouter(e)
e.Static("/", "./public")
e.GET("/", defaultHandler)
go func() {
if err := e.Start(port); err != nil {
e.Logger.Info("Shutting down the server...")
}
}()
signCh := make(chan os.Signal)
signal.Notify(signCh, os.Interrupt)
signal.Notify(signCh, os.Kill)
sig := <-signCh
log.Println("Received terminal, graceful shutdown.", sig)
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.")
}