81 lines
1.9 KiB
Go
81 lines
1.9 KiB
Go
|
package server
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"net/http"
|
||
|
"os"
|
||
|
"strings"
|
||
|
"time"
|
||
|
|
||
|
"git.staur.ca/stobbsm/clustvirt/cluster"
|
||
|
"git.staur.ca/stobbsm/clustvirt/lib/log"
|
||
|
"git.staur.ca/stobbsm/clustvirt/router"
|
||
|
"git.staur.ca/stobbsm/clustvirt/router/htmx"
|
||
|
"git.staur.ca/stobbsm/clustvirt/router/middleware"
|
||
|
"github.com/go-chi/chi/v5"
|
||
|
)
|
||
|
|
||
|
// Server represents an HTTP server that uses chi for routes
|
||
|
type Server struct {
|
||
|
bindAddr string
|
||
|
ssl bool
|
||
|
c *cluster.Cluster
|
||
|
r chi.Router
|
||
|
}
|
||
|
|
||
|
// New creates a new HTTP Server instance.
|
||
|
// Requires the IP and port number to bind to
|
||
|
func New(listen string, port int, cluster *cluster.Cluster) *Server {
|
||
|
s := &Server{bindAddr: fmt.Sprintf("%s:%d", listen, port), c: cluster}
|
||
|
|
||
|
return s
|
||
|
}
|
||
|
|
||
|
// Start starts the server and initializes the router and common middleware
|
||
|
func (s *Server) Start() {
|
||
|
tstart := time.Now()
|
||
|
defer func() {
|
||
|
log.Info("router.Server.Start").
|
||
|
Dur("upTime", time.Since(tstart)).
|
||
|
Msg("http server stopped")
|
||
|
}()
|
||
|
s.r = chi.NewRouter()
|
||
|
|
||
|
indev, _ := os.LookupEnv("CLUSTVIRT_DEV")
|
||
|
indev = strings.ToLower(indev)
|
||
|
switch indev {
|
||
|
case "true":
|
||
|
fallthrough
|
||
|
case "1":
|
||
|
fallthrough
|
||
|
case "yes":
|
||
|
fallthrough
|
||
|
case "on":
|
||
|
s.AddMiddleware(middleware.NoCache)
|
||
|
s.r.Get("/_/debug", middleware.Profiler().ServeHTTP)
|
||
|
}
|
||
|
// Add routes
|
||
|
s.baseRoutes()
|
||
|
if err := s.AddSubRouter(htmx.Htmx); err != nil {
|
||
|
log.Error("server.Start").
|
||
|
Str("subroute", "htmx").
|
||
|
Err(err).Send()
|
||
|
}
|
||
|
// Start the server
|
||
|
if err := http.ListenAndServe(s.bindAddr, s.r); err != nil {
|
||
|
log.Error("router.Server.Start").
|
||
|
Str("bindaddr", s.bindAddr).
|
||
|
Err(err).Send()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// AddMiddleware appends middleware to the chi router
|
||
|
func (s *Server) AddMiddleware(m ...func(h http.Handler) http.Handler) {
|
||
|
s.r.Use(m...)
|
||
|
}
|
||
|
|
||
|
// AddSubRouter attachs a SubRouter using it's MountTo method
|
||
|
func (s *Server) AddSubRouter(sr router.SubRouter) error {
|
||
|
return sr.MountTo(s.c, s.r)
|
||
|
}
|