octopush/internal/server/http_server.go

72 lines
1.6 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"
"git.front.kjuulh.io/kjuulh/curre"
"git.front.kjuulh.io/kjuulh/kraken/internal/serverdeps"
2022-09-11 13:43:29 +02:00
"github.com/gin-gonic/gin"
2022-09-10 20:20:49 +02:00
)
func NewHttpServer(deps *serverdeps.ServerDeps) curre.Component {
return curre.NewFunctionalComponent(&curre.FunctionalComponent{
2022-09-11 13:43:29 +02:00
StartFunc: func(_ *curre.FunctionalComponent, _ context.Context) error {
2022-09-10 20:20:49 +02:00
handler := http.NewServeMux()
handler.HandleFunc(
"/health/ready",
func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte("ready"))
w.WriteHeader(http.StatusOK)
})
http.ListenAndServe("127.0.0.1:3000", handler)
return nil
},
},
)
}
2022-09-11 13:43:29 +02:00
func NewGinHttpServer(_ *serverdeps.ServerDeps) curre.Component {
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-11 13:43:29 +02:00
app = gin.Default()
app.UseH2C = true
2022-09-10 20:20:49 +02:00
2022-09-11 13:43:29 +02:00
healthRoute := app.Group("/health")
healthRoute.GET("/ready", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "healthy",
})
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 {
if server != nil {
server.Shutdown(ctx)
2022-09-10 20:20:49 +02:00
}
return nil
},
})
}