2020-09-15 23:09:07 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2020-09-17 18:01:18 +02:00
|
|
|
"context"
|
2020-09-26 23:27:30 +02:00
|
|
|
"go-rest-api/handler"
|
2020-09-17 18:01:18 +02:00
|
|
|
"log"
|
2020-09-26 23:27:30 +02:00
|
|
|
"net/http"
|
2020-09-17 18:01:18 +02:00
|
|
|
"os"
|
|
|
|
"os/signal"
|
|
|
|
"time"
|
2020-09-26 23:27:30 +02:00
|
|
|
|
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
"github.com/labstack/echo/v4/middleware"
|
2020-09-15 23:09:07 +02:00
|
|
|
)
|
|
|
|
|
2020-09-26 23:27:30 +02:00
|
|
|
var port = ":8000"
|
|
|
|
|
2020-09-15 23:09:07 +02:00
|
|
|
func main() {
|
2020-09-30 22:12:50 +02:00
|
|
|
// framework setup
|
2020-09-26 23:27:30 +02:00
|
|
|
e := echo.New()
|
|
|
|
e.Use(middleware.Logger())
|
|
|
|
e.Use(middleware.Recover())
|
|
|
|
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
|
2020-09-29 22:35:59 +02:00
|
|
|
AllowOrigins: []string{"http://localhost:8000"}, // FIXME use env var or sth like that
|
2020-09-26 23:27:30 +02:00
|
|
|
AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
|
|
|
|
}))
|
|
|
|
|
|
|
|
handler.AttachArticleHandlersToRouter(e)
|
2020-09-29 22:35:59 +02:00
|
|
|
handler.AttachProductHandlersToRouter(e)
|
2020-09-26 23:27:30 +02:00
|
|
|
|
|
|
|
e.Static("/", "./public")
|
|
|
|
e.GET("/", defaultHandler)
|
2020-09-17 18:01:18 +02:00
|
|
|
|
|
|
|
go func() {
|
2020-09-26 23:27:30 +02:00
|
|
|
if err := e.Start(port); err != nil {
|
|
|
|
e.Logger.Info("Shutting down the server...")
|
|
|
|
}
|
2020-09-17 18:01:18 +02:00
|
|
|
}()
|
|
|
|
|
|
|
|
signCh := make(chan os.Signal)
|
|
|
|
signal.Notify(signCh, os.Interrupt)
|
|
|
|
signal.Notify(signCh, os.Kill)
|
|
|
|
|
|
|
|
sig := <-signCh
|
2020-09-26 23:27:30 +02:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
2020-09-17 18:01:18 +02:00
|
|
|
|
2020-09-26 23:27:30 +02:00
|
|
|
func defaultHandler(c echo.Context) error {
|
|
|
|
return echo.NewHTTPError(http.StatusMethodNotAllowed, "Method not allowed.")
|
2020-09-15 23:09:07 +02:00
|
|
|
}
|