octopush/internal/server/http_server.go

55 lines
1.3 KiB
Go
Raw Normal View History

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"
"time"
2022-09-10 20:20:49 +02:00
"git.front.kjuulh.io/kjuulh/curre"
"git.front.kjuulh.io/kjuulh/octopush/internal/api"
"git.front.kjuulh.io/kjuulh/octopush/internal/serverdeps"
ginzap "github.com/gin-contrib/zap"
2022-09-11 13:43:29 +02:00
"github.com/gin-gonic/gin"
"go.uber.org/zap"
2022-09-10 20:20:49 +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 {
app = gin.New()
2022-09-11 13:43:29 +02:00
app.UseH2C = true
app.Use(ginzap.Ginzap(logger, time.RFC3339, true))
app.Use(ginzap.RecoveryWithZap(logger, true))
2022-09-10 20:20:49 +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 {
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
},
})
}