octopush/internal/server/http_server.go

83 lines
2.1 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"
2022-09-11 22:56:54 +02:00
"time"
2022-09-10 20:20:49 +02:00
"git.front.kjuulh.io/kjuulh/curre"
2022-09-11 22:56:54 +02:00
"git.front.kjuulh.io/kjuulh/kraken/internal/commands"
2022-09-10 20:20:49 +02:00
"git.front.kjuulh.io/kjuulh/kraken/internal/serverdeps"
2022-09-11 22:56:54 +02:00
"git.front.kjuulh.io/kjuulh/kraken/internal/services/jobs"
2022-09-11 13:43:29 +02:00
"github.com/gin-gonic/gin"
2022-09-11 22:56:54 +02:00
"github.com/google/uuid"
"go.uber.org/zap"
2022-09-10 20:20:49 +02:00
)
2022-09-11 22:56:54 +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-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 22:56:54 +02:00
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)
})
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-11 22:56:54 +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
},
})
}