sirius/internal/server/app.go

107 lines
2.1 KiB
Go

package server
import (
"context"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
ginlogrus "github.com/toorop/gin-logrus"
"github.com/gin-contrib/cors"
"gitstore.ru/tolikproh/sirius/internal/controller/handler"
"gitstore.ru/tolikproh/sirius/internal/model"
"net/http"
"os"
"os/signal"
"time"
)
type Server struct {
httpServer *http.Server
log *logrus.Logger
cfg *model.Config
}
func New(cfg *model.Config, log *logrus.Logger) *Server {
// Initiate an S3 compatible client
return &Server{
httpServer: &http.Server{
Addr: ":" + cfg.Srv.Port,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
},
cfg: cfg, log: log}
}
func (a *Server) Run() error {
a.log.Debug("start server")
gin.SetMode(validMode(a.cfg.Srv.Mode))
router := gin.New()
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,
}))
router.Use(
gin.Recovery(),
ginlogrus.Logger(a.log),
)
h := handler.New(a.cfg, a.log)
// API endpoints
api := router.Group("/api")
api.POST("/sirius", h.GinConvert)
// HTTP Server
a.httpServer.Handler = router
go func() {
if err := a.httpServer.ListenAndServe(); err != nil {
a.log.Fatalf("Failed to listen and serve: %+v", err)
return
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, os.Interrupt)
<-quit
a.log.Println("Shutdown Server ...")
ctx, cansel := context.WithTimeout(context.Background(), 5*time.Second)
defer cansel()
select {
case <-ctx.Done():
a.log.Println("timeout of 5 seconds.")
}
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
}