esxlib/ui/server.go

127 lines
2.7 KiB
Go

package ui
import (
"net/http"
"time"
"esxlib/pkg/utils"
"esxlib/service"
"git.twelvetwelve.org/library/core/log"
"git.twelvetwelve.org/library/snap"
"git.twelvetwelve.org/library/snap/auth"
"github.com/madflojo/testcerts"
)
type Server struct {
snap *snap.Server
api *service.CloudServer
}
type handlerMap struct {
path string
template string
redirect string
auth bool
methods []string // default is get
handler func(ctx *snap.Context)
}
func throwError(ctx *snap.Context, code int, err error) {
ctx.Error(code, err.Error())
}
func (s *Server) LogRequest(ctx *snap.Context) {
host := ctx.GetRequest().Header.Get("x-forwarded-for")
if host == "" {
host = ctx.GetRequest().RemoteAddr
}
user := ctx.GetUser()
if user == "" {
user = "--"
}
log.Infof("%s %s %s %s\n", host, user, ctx.GetRequest().Method, ctx.GetRequest().RequestURI)
}
func (s *Server) RenderWithMeta(ctx *snap.Context, tmpl string, meta map[string]string, content interface{}) error {
ctx.RenderWithMeta(tmpl, meta, content)
return nil
}
func (s *Server) uiHandlerWithUserAndError(handler func(user string, ctx *snap.Context) error, allowedGroups []string) func(ctx *snap.Context) {
return func(ctx *snap.Context) {
s.LogRequest(ctx)
if err := handler("", ctx); err != nil {
throwError(ctx, http.StatusBadRequest, err)
}
}
}
func (s *Server) mustRunServer(tls bool) {
// dbs := s.dbs
// authenticator := s.auth
srv := s.snap
srv.SetDebug(true)
srv.WithHealthCheck("1.0.0", time.Now().String(), func() (bool, string) {
return true, "ok"
})
//srv.WithTemplateFuncs(templateFuncs)
srv.WithRootFileSystem(http.Dir("./web/"))
srv.WithMetadata(map[string]string{
"build.version": "1.0",
"build.time": time.Now().String(),
})
srv.SetTemplatePath("/templates")
srv.WithStaticFiles("/static")
s.setupHandlers()
// tls is needed for local development since otherwise the location api does not work in the browser
if tls {
err := testcerts.GenerateCertsToFile("server.cert", "server.key")
if err != nil {
log.Panicf("could not create tls certs")
}
if err := srv.ServeTLS("server.key", "server.cert"); err != nil {
log.Panicf("%v\n", err)
}
}
if err := srv.Serve(); err != nil {
log.Panicf("%v\n", err)
}
}
func (s *Server) Run(tls bool) {
s.mustRunServer(tls)
}
func New(path string) (*Server, error) {
config := &service.Config{}
if err := utils.UnmarshalFromFile(path, config); err != nil {
return nil, err
}
api, err := service.NewService(config)
if err != nil {
return nil, err
}
authenticator := auth.NewNoAuth()
srv := snap.New(config.ListenAddress, "./", authenticator)
s := &Server{
snap: srv,
api: api,
}
log.Printf("Listening on: http://localhost%s\n", config.ListenAddress)
return s, nil
}