package server import ( "fmt" "net/http" "os" "strings" "time" "git.staur.ca/stobbsm/clustvirt/cluster" "git.staur.ca/stobbsm/clustvirt/router/htmx" log "git.staur.ca/stobbsm/simplelog" router "git.staur.ca/stobbsm/simpleroute" "git.staur.ca/stobbsm/simpleroute/middleware" ) // Server represents an HTTP server that uses net/http ServeMux to route requests // Originally done with chi, but a migration to the new net/http patterns seems like // a good choice to reduce dependencies, but does mean middleware needs to be implemented // in the server type Server struct { bindAddr string ssl bool c *cluster.Cluster r *router.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 = router.New() indev, _ := os.LookupEnv("CLUSTVIRT_DEV") indev = strings.ToLower(indev) switch indev { case "true": fallthrough case "1": fallthrough case "yes": fallthrough case "on": s.r.AddMiddleware(middleware.NoCache) } s.r.AddMiddleware(middleware.Logger) // Add routes s.baseRoutes() if err := s.r.AddSubRouter("/htmx", htmx.Routes(s.c)); 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() } }