sirius/internal/server/app.go

107 lines
2.1 KiB
Go
Raw Permalink Normal View History

2023-04-17 05:00:34 +03:00
package server
import (
"context"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
ginlogrus "github.com/toorop/gin-logrus"
2023-04-17 05:00:34 +03:00
2023-04-22 04:29:10 +03:00
"github.com/gin-contrib/cors"
2023-04-17 08:48:09 +03:00
"gitstore.ru/tolikproh/sirius/internal/controller/handler"
"gitstore.ru/tolikproh/sirius/internal/model"
2023-04-17 05:00:34 +03:00
"net/http"
"os"
"os/signal"
"time"
)
type Server struct {
2023-04-17 05:00:34 +03:00
httpServer *http.Server
log *logrus.Logger
cfg *model.Config
2023-04-17 05:00:34 +03:00
}
func New(cfg *model.Config, log *logrus.Logger) *Server {
2023-04-17 05:00:34 +03:00
// Initiate an S3 compatible client
return &Server{
2023-04-17 08:48:09 +03:00
httpServer: &http.Server{
Addr: ":" + cfg.Srv.Port,
2023-04-17 08:48:09 +03:00
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
},
cfg: cfg, log: log}
2023-04-17 05:00:34 +03:00
}
func (a *Server) Run() error {
a.log.Debug("start server")
gin.SetMode(validMode(a.cfg.Srv.Mode))
router := gin.New()
2023-04-17 05:00:34 +03:00
2023-04-22 04:29:10 +03:00
router.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "HEAD"},
AllowHeaders: []string{"Origin", "Authorization", "Content-Type", "Content-Type: multipart/form-data"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
}))
2023-04-17 05:00:34 +03:00
router.Use(
gin.Recovery(),
ginlogrus.Logger(a.log),
2023-04-17 05:00:34 +03:00
)
h := handler.New(a.cfg, a.log)
2023-04-17 05:00:34 +03:00
// API endpoints
api := router.Group("/api")
api.POST("/sirius", h.GinConvert)
2023-04-17 05:00:34 +03:00
// HTTP Server
2023-04-17 08:48:09 +03:00
a.httpServer.Handler = router
2023-04-17 05:00:34 +03:00
go func() {
if err := a.httpServer.ListenAndServe(); err != nil {
a.log.Fatalf("Failed to listen and serve: %+v", err)
return
2023-04-17 05:00:34 +03:00
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, os.Interrupt)
<-quit
a.log.Println("Shutdown Server ...")
2023-04-17 05:00:34 +03:00
ctx, cansel := context.WithTimeout(context.Background(), 5*time.Second)
defer cansel()
select {
case <-ctx.Done():
a.log.Println("timeout of 5 seconds.")
}
2023-04-17 05:00:34 +03:00
return a.httpServer.Shutdown(ctx)
}
func validMode(mode string) string {
switch mode {
case gin.ReleaseMode:
return gin.ReleaseMode
case gin.DebugMode:
return gin.DebugMode
case gin.TestMode:
return gin.TestMode
}
return gin.TestMode
}