2022-09-10 20:20:49 +02:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2022-09-11 13:43:29 +02:00
|
|
|
"errors"
|
2022-09-10 20:20:49 +02:00
|
|
|
"net/http"
|
2022-09-12 22:12:02 +02:00
|
|
|
"time"
|
2022-09-10 20:20:49 +02:00
|
|
|
|
|
|
|
"git.front.kjuulh.io/kjuulh/curre"
|
2022-09-21 11:06:53 +02:00
|
|
|
"git.front.kjuulh.io/kjuulh/octopush/internal/api"
|
|
|
|
"git.front.kjuulh.io/kjuulh/octopush/internal/serverdeps"
|
2022-09-12 22:12:02 +02:00
|
|
|
ginzap "github.com/gin-contrib/zap"
|
2022-09-11 13:43:29 +02:00
|
|
|
"github.com/gin-gonic/gin"
|
2022-09-12 22:12:02 +02:00
|
|
|
"go.uber.org/zap"
|
2022-09-10 20:20:49 +02:00
|
|
|
)
|
|
|
|
|
2022-09-12 22:12:02 +02:00
|
|
|
func NewGinHttpServer(logger *zap.Logger, deps *serverdeps.ServerDeps) curre.Component {
|
2022-09-11 13:43:29 +02:00
|
|
|
var app *gin.Engine
|
|
|
|
var server *http.Server
|
2022-09-10 20:20:49 +02:00
|
|
|
|
|
|
|
return curre.NewFunctionalComponent(&curre.FunctionalComponent{
|
|
|
|
InitFunc: func(_ *curre.FunctionalComponent, _ context.Context) error {
|
2022-09-12 22:12:02 +02:00
|
|
|
app = gin.New()
|
2022-09-11 13:43:29 +02:00
|
|
|
app.UseH2C = true
|
2022-09-12 22:12:02 +02:00
|
|
|
app.Use(ginzap.Ginzap(logger, time.RFC3339, true))
|
|
|
|
app.Use(ginzap.RecoveryWithZap(logger, true))
|
2022-09-10 20:20:49 +02:00
|
|
|
|
2022-09-12 22:12:02 +02:00
|
|
|
api.BuildApi(logger, app, deps)
|
2022-09-10 20:20:49 +02:00
|
|
|
|
2022-09-11 13:43:29 +02:00
|
|
|
server = &http.Server{
|
|
|
|
Addr: "127.0.0.1:3000",
|
|
|
|
Handler: app,
|
|
|
|
}
|
|
|
|
|
2022-09-10 20:20:49 +02:00
|
|
|
return nil
|
|
|
|
},
|
|
|
|
StartFunc: func(_ *curre.FunctionalComponent, _ context.Context) error {
|
2022-09-11 13:43:29 +02:00
|
|
|
if server != nil {
|
|
|
|
err := server.ListenAndServe()
|
|
|
|
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
|
|
return err
|
|
|
|
}
|
2022-09-10 20:20:49 +02:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
},
|
2022-09-11 13:43:29 +02:00
|
|
|
StopFunc: func(_ *curre.FunctionalComponent, ctx context.Context) error {
|
2022-09-12 22:12:02 +02:00
|
|
|
ctx, _ = context.WithTimeout(ctx, time.Second*10)
|
2022-09-11 13:43:29 +02:00
|
|
|
if server != nil {
|
|
|
|
server.Shutdown(ctx)
|
2022-09-10 20:20:49 +02:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
})
|
|
|
|
}
|