alice-lg/pkg/http/server.go

78 lines
1.9 KiB
Go
Raw Permalink Normal View History

2021-11-15 21:43:22 +01:00
// Package http provides the server and API implementation
// for the webclient. The webclient's static files are also served.
2021-10-25 22:03:10 +02:00
package http
import (
2021-12-07 19:11:11 +01:00
"context"
2021-10-25 22:03:10 +02:00
"log"
"net/http"
2021-10-28 16:34:29 +02:00
"time"
2021-10-25 22:03:10 +02:00
"github.com/alice-lg/alice-lg/pkg/config"
"github.com/alice-lg/alice-lg/pkg/store"
2022-01-14 11:04:14 +01:00
"github.com/jackc/pgx/v4/pgxpool"
2021-10-25 22:03:10 +02:00
"github.com/julienschmidt/httprouter"
)
// Server provides the HTTP server for the API
// and the assets.
type Server struct {
2021-10-28 16:34:29 +02:00
*http.Server
2021-10-25 22:03:10 +02:00
cfg *config.Config
routesStore *store.RoutesStore
neighborsStore *store.NeighborsStore
2022-01-14 11:04:14 +01:00
pool *pgxpool.Pool
2021-10-25 22:03:10 +02:00
}
// NewServer creates a new server
func NewServer(
cfg *config.Config,
2022-01-14 11:04:14 +01:00
pool *pgxpool.Pool,
2021-10-25 22:03:10 +02:00
routesStore *store.RoutesStore,
neighborsStore *store.NeighborsStore,
) *Server {
return &Server{
cfg: cfg,
routesStore: routesStore,
neighborsStore: neighborsStore,
2022-01-14 11:04:14 +01:00
pool: pool,
2021-10-25 22:03:10 +02:00
}
}
// Start starts a HTTP server and begins to listen
// on the configured port.
2022-06-15 15:49:45 +02:00
func (s *Server) Start(ctx context.Context) {
2021-10-25 22:03:10 +02:00
router := httprouter.New()
2021-10-28 16:34:29 +02:00
// Register routes
2021-12-07 19:11:11 +01:00
if err := s.webRegisterAssets(ctx, router); err != nil {
2021-10-25 22:03:10 +02:00
log.Fatal(err)
}
2021-10-26 23:11:42 +02:00
if err := s.apiRegisterEndpoints(router); err != nil {
2021-10-25 22:03:10 +02:00
log.Fatal(err)
}
2022-06-15 15:49:45 +02:00
2021-10-28 16:34:29 +02:00
httpTimeout := time.Duration(s.cfg.Server.HTTPTimeout) * time.Second
log.Println("Web server HTTP timeout set to:", httpTimeout)
2024-01-15 11:16:13 +01:00
log.Println("Listening on:", s.cfg.Server.Listen)
if s.cfg.Server.EnablePrefixLookup {
log.Println("Prefix Lookup (Search): enabled")
log.Println("Prefix Lookup Community Filter Cutoff:",
s.cfg.Server.PrefixLookupCommunityFilterCutoff)
} else {
log.Println("Prefix Lookup (Search): disabled")
}
2021-10-28 16:34:29 +02:00
s.Server = &http.Server{
Addr: s.cfg.Server.Listen,
Handler: router,
ReadTimeout: httpTimeout,
WriteTimeout: httpTimeout,
IdleTimeout: httpTimeout,
}
2021-10-25 22:03:10 +02:00
// Start http server
2021-10-28 16:34:29 +02:00
log.Fatal(s.ListenAndServe())
2021-10-25 22:03:10 +02:00
}