go-scopes/server/server.go

66 lines
1.3 KiB
Go

package server
import (
"fmt"
"net/http"
lib "git.sr.ht/~cco/go-scopes"
"git.sr.ht/~cco/go-scopes/core"
"github.com/gin-gonic/gin"
)
type ServerState struct {
server *http.Server
}
func Start(ctx lib.Context) {
//gin.SetMode(gin.ReleaseMode)
lib.GetCfg[*Cfg](ctx).BaseCfg.WithDoneHandler(HandleDone)
Serve(ctx)
lib.RunCtx(ctx, core.Listen)
}
func HandleDone(ctx lib.Context) bool {
lib.GetState[*ServerState](ctx).server.Shutdown(ctx)
return false
}
func Serve(ctx lib.Context) {
r := gin.New()
r.Use(gin.Recovery())
r.Use(Logger(ctx))
/*r.GET("/*action", func(c *gin.Context) {
c.String(http.StatusOK, "Hello World")
})*/
cfg := ctx.Config().(*Cfg)
for _, rcfg := range cfg.routes {
setRoute(ctx, rcfg, r)
}
srv := &http.Server{
Addr: ":8123",
Handler: r,
}
ctx.WithState(&ServerState{
server: srv,
})
lib.RunCtx(ctx, func(ctx lib.Context) {
srv.ListenAndServe()
})
}
func setRoute(ctx lib.Context, rcfg routeCfg, r *gin.Engine) {
switch spec := rcfg.spec.(type) {
case *fsSpec:
r.Static(rcfg.path, spec.docRoot)
case *rcellSpec:
r.Match(rcfg.methods, rcfg.path, func(c *gin.Context) {
RCell(ctx, spec, c)
})
}
}
// RCell (request / response handler cell) implementation
func RCell(ctx lib.Context, spec *rcellSpec, gc *gin.Context) {
fmt.Println("*** RCell called")
}