octopush/internal/server/http_server.go
2022-09-11 22:56:54 +02:00

83 lines
2.1 KiB
Go

package server
import (
"context"
"errors"
"net/http"
"time"
"git.front.kjuulh.io/kjuulh/curre"
"git.front.kjuulh.io/kjuulh/kraken/internal/commands"
"git.front.kjuulh.io/kjuulh/kraken/internal/serverdeps"
"git.front.kjuulh.io/kjuulh/kraken/internal/services/jobs"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"go.uber.org/zap"
)
func NewGinHttpServer(logger *zap.Logger, deps *serverdeps.ServerDeps) curre.Component {
var app *gin.Engine
var server *http.Server
return curre.NewFunctionalComponent(&curre.FunctionalComponent{
InitFunc: func(_ *curre.FunctionalComponent, _ context.Context) error {
app = gin.Default()
app.UseH2C = true
healthRoute := app.Group("/health")
healthRoute.GET("/ready", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "healthy",
})
})
commandRoute := app.Group("commands")
commandRoute.POST("processRepos", func(c *gin.Context) {
type processReposRequest struct {
RepositoryUrls []string `json:"repositoryUrls"`
}
var request processReposRequest
err := c.BindJSON(&request)
if err != nil {
logger.Info("could not bind request", zap.String("request", "processRepo"), zap.Error(err))
c.AbortWithStatus(http.StatusBadRequest)
return
}
jobId := uuid.New().String()
go func(repositoryUrls []string, jobId string) {
ctx := context.WithValue(context.Background(), jobs.JobId{}, jobId)
processRepos := commands.NewProcessRepos(logger, deps)
err = processRepos.Process(ctx, repositoryUrls, nil)
}(request.RepositoryUrls, jobId)
c.Status(http.StatusAccepted)
})
server = &http.Server{
Addr: "127.0.0.1:3000",
Handler: app,
}
return nil
},
StartFunc: func(_ *curre.FunctionalComponent, _ context.Context) error {
if server != nil {
err := server.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
}
return nil
},
StopFunc: func(_ *curre.FunctionalComponent, ctx context.Context) error {
ctx, _ = context.WithTimeout(ctx, time.Second*10)
if server != nil {
server.Shutdown(ctx)
}
return nil
},
})
}