2021-01-09 20:39:05 +00:00
|
|
|
package httpserver
|
|
|
|
|
|
|
|
import (
|
2021-01-11 21:39:33 +00:00
|
|
|
"context"
|
2021-01-09 20:39:05 +00:00
|
|
|
"crypto/tls"
|
2021-10-24 16:39:48 +00:00
|
|
|
"net"
|
2021-01-09 20:39:05 +00:00
|
|
|
"net/http"
|
2021-10-24 16:39:48 +00:00
|
|
|
"sync"
|
2021-01-09 20:39:05 +00:00
|
|
|
|
2022-11-05 07:29:17 +00:00
|
|
|
intlog "log"
|
|
|
|
|
2022-11-05 07:45:48 +00:00
|
|
|
"github.com/flosch/pongo2/v6"
|
2021-01-09 20:39:05 +00:00
|
|
|
"github.com/gin-gonic/gin"
|
2022-11-05 07:29:17 +00:00
|
|
|
"github.com/rs/zerolog/log"
|
2021-01-09 20:39:05 +00:00
|
|
|
"go.sebtobie.de/httpserver/auth"
|
2021-11-11 22:05:07 +00:00
|
|
|
"go.sebtobie.de/httpserver/constants"
|
2021-11-07 17:51:39 +00:00
|
|
|
"go.sebtobie.de/httpserver/funcs"
|
2021-01-19 22:44:35 +00:00
|
|
|
"go.sebtobie.de/httpserver/menus"
|
2021-11-11 22:06:48 +00:00
|
|
|
"go.sebtobie.de/httpserver/middleware"
|
2021-10-24 16:39:48 +00:00
|
|
|
"go.sebtobie.de/httpserver/templates"
|
2021-01-09 20:39:05 +00:00
|
|
|
)
|
|
|
|
|
2021-11-06 12:42:07 +00:00
|
|
|
func init() {
|
|
|
|
gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {
|
2021-11-07 17:51:39 +00:00
|
|
|
log.Debug().Msgf("%-4s(%02d): %-20s %s", httpMethod, nuHandlers, absolutePath, handlerName)
|
2021-11-06 12:42:07 +00:00
|
|
|
}
|
2021-11-07 17:51:39 +00:00
|
|
|
gin.SetMode(gin.DebugMode)
|
2021-11-06 12:42:07 +00:00
|
|
|
}
|
|
|
|
|
2021-01-09 20:39:05 +00:00
|
|
|
// Config that is used to map the toml config to the settings that are used.
|
|
|
|
type Config struct {
|
2021-11-11 22:06:48 +00:00
|
|
|
Addr []string
|
|
|
|
TLSAddr []string
|
|
|
|
TLSconfig *tls.Config `toml:"-"`
|
|
|
|
Certfile string
|
|
|
|
Keyfile string
|
|
|
|
Sites map[string]SiteConfig
|
|
|
|
Middleware map[string]middleware.Config
|
2021-01-09 20:39:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Server is an wrapper for the *http.Server and *gin.Engine
|
|
|
|
type Server struct {
|
2021-11-06 19:59:56 +00:00
|
|
|
http *http.Server
|
|
|
|
Conf *Config
|
|
|
|
mrouter map[string]*gin.Engine
|
|
|
|
sites map[string]Site
|
2021-01-24 15:25:58 +00:00
|
|
|
menu []menus.Menu
|
2021-11-10 18:05:52 +00:00
|
|
|
template *pongo2.TemplateSet
|
2021-01-24 15:25:58 +00:00
|
|
|
NotFoundHandler http.Handler
|
2021-10-24 16:39:48 +00:00
|
|
|
routines sync.WaitGroup
|
2021-11-06 19:59:56 +00:00
|
|
|
setup bool
|
|
|
|
authh auth.AuthenticationHandler
|
2021-11-07 17:51:39 +00:00
|
|
|
middleware gin.HandlersChain
|
2021-11-11 22:06:48 +00:00
|
|
|
advmiddleware map[string]middleware.Middleware
|
2021-01-24 15:25:58 +00:00
|
|
|
}
|
|
|
|
|
2021-11-06 12:42:07 +00:00
|
|
|
// CreateServer creates an server that can be run in a coroutine.
|
|
|
|
func CreateServer() *Server {
|
|
|
|
log.Info().Msg("Redirect logging output to phuslu/log")
|
2022-11-05 07:29:17 +00:00
|
|
|
gin.DefaultErrorWriter = log.Logger.With().Str("source", "GIN").Logger()
|
|
|
|
gin.DefaultWriter = log.Logger.With().Str("source", "GIN").Logger()
|
2021-11-06 12:42:07 +00:00
|
|
|
log.Info().Msg("Creating HTTP-Server")
|
|
|
|
var server = &Server{
|
2021-11-07 17:51:39 +00:00
|
|
|
Conf: &Config{
|
2022-11-13 09:36:51 +00:00
|
|
|
TLSconfig: &tls.Config{},
|
|
|
|
Sites: map[string]SiteConfig{},
|
|
|
|
Middleware: map[string]middleware.Config{},
|
2021-11-07 17:51:39 +00:00
|
|
|
},
|
2021-11-06 19:59:56 +00:00
|
|
|
mrouter: map[string]*gin.Engine{},
|
|
|
|
authh: &auth.AnonAccountHandler{},
|
|
|
|
menu: []menus.Menu{},
|
|
|
|
NotFoundHandler: http.NotFoundHandler(),
|
2021-11-07 17:51:39 +00:00
|
|
|
sites: map[string]Site{},
|
|
|
|
middleware: gin.HandlersChain{},
|
2021-11-10 18:05:52 +00:00
|
|
|
template: pongo2.NewSet("templates", &templates.EmptyLoader{}),
|
2022-11-13 09:36:51 +00:00
|
|
|
advmiddleware: map[string]middleware.Middleware{},
|
2021-01-24 15:25:58 +00:00
|
|
|
}
|
2021-11-06 12:42:07 +00:00
|
|
|
server.http = &http.Server{
|
2022-11-05 07:29:17 +00:00
|
|
|
ErrorLog: intlog.New(log.Logger, "", 0),
|
2021-11-06 12:42:07 +00:00
|
|
|
Handler: http.HandlerFunc(server.DomainRouter),
|
|
|
|
}
|
|
|
|
return server
|
2021-01-09 20:39:05 +00:00
|
|
|
}
|
|
|
|
|
2021-10-24 16:39:48 +00:00
|
|
|
// runPort runs a listener on the port. his enables th server to serve more than a address.
|
|
|
|
func (s *Server) runPort(address string, tls bool) {
|
2021-11-07 17:51:39 +00:00
|
|
|
defer s.routines.Done()
|
2021-10-24 16:39:48 +00:00
|
|
|
var socket net.Listener
|
|
|
|
var err error
|
2021-11-07 17:51:39 +00:00
|
|
|
var unix string
|
|
|
|
|
|
|
|
if funcs.IsTCP(address) {
|
2021-10-24 16:39:48 +00:00
|
|
|
socket, err = net.Listen("tcp", address)
|
2021-11-07 17:51:39 +00:00
|
|
|
}
|
|
|
|
if funcs.IsUnix(address) {
|
|
|
|
unix = "Unix-"
|
2021-10-24 16:39:48 +00:00
|
|
|
socket, err = net.Listen("unix", address)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
log.Error().Err(err).Msgf("failed to open socket on %s", address)
|
2021-11-07 17:51:39 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if socket == nil {
|
|
|
|
log.Error().Msg("Failed to identify the sockettype")
|
|
|
|
return
|
2021-10-24 16:39:48 +00:00
|
|
|
}
|
|
|
|
if tls {
|
2021-11-07 17:51:39 +00:00
|
|
|
log.Info().Msgf("starting listen on secure %ssocket %s", unix, address)
|
2021-11-06 12:42:07 +00:00
|
|
|
err = s.http.ServeTLS(socket, s.Conf.Certfile, s.Conf.Keyfile)
|
2021-10-24 16:39:48 +00:00
|
|
|
} else {
|
2021-11-07 17:51:39 +00:00
|
|
|
log.Info().Msgf("starting listen on %ssocket %s", unix, address)
|
2021-10-24 16:39:48 +00:00
|
|
|
err = s.http.Serve(socket)
|
|
|
|
}
|
|
|
|
if err != http.ErrServerClosed {
|
|
|
|
log.Error().Err(err).Msg("Socket unexpected exited")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-06 19:59:56 +00:00
|
|
|
// SetAuthentication sets the handler that is responsible for authentication
|
|
|
|
func (s *Server) SetAuthentication(a auth.AuthenticationHandler) {
|
|
|
|
s.authh = a
|
|
|
|
}
|
|
|
|
|
2021-01-09 20:39:05 +00:00
|
|
|
// StartServer starts the server as configured and sends the errormessage to the log.
|
2021-10-24 16:39:48 +00:00
|
|
|
// it blocks until all ports are closed.
|
2021-01-09 20:39:05 +00:00
|
|
|
func (s *Server) StartServer() {
|
2021-11-06 19:59:56 +00:00
|
|
|
if !s.setup {
|
|
|
|
log.Error().Msg("Server not set up")
|
|
|
|
return
|
|
|
|
}
|
2021-01-09 20:39:05 +00:00
|
|
|
log.Info().Msg("Starting server")
|
2021-11-06 12:42:07 +00:00
|
|
|
s.http.TLSConfig = s.Conf.TLSconfig
|
|
|
|
if s.Conf.Certfile != "" && s.Conf.Keyfile != "" {
|
|
|
|
for _, addr := range s.Conf.TLSAddr {
|
2021-10-24 16:39:48 +00:00
|
|
|
s.routines.Add(1)
|
|
|
|
go s.runPort(addr, true)
|
|
|
|
}
|
|
|
|
}
|
2021-11-06 12:42:07 +00:00
|
|
|
for _, addr := range s.Conf.Addr {
|
2021-11-07 17:51:39 +00:00
|
|
|
s.routines.Add(1)
|
2021-10-24 16:39:48 +00:00
|
|
|
go s.runPort(addr, false)
|
2021-01-09 20:39:05 +00:00
|
|
|
}
|
2021-10-24 16:39:48 +00:00
|
|
|
s.routines.Wait()
|
2021-01-09 20:39:05 +00:00
|
|
|
}
|
|
|
|
|
2021-01-23 10:14:33 +00:00
|
|
|
// DomainRouter redirects the requests to the routers of the domains
|
2021-01-24 15:25:58 +00:00
|
|
|
func (s *Server) DomainRouter(w http.ResponseWriter, r *http.Request) {
|
|
|
|
var domain string
|
|
|
|
if r.URL.Host != "" {
|
|
|
|
domain = r.URL.Host
|
|
|
|
} else if r.Host != "" {
|
|
|
|
domain = r.Host
|
|
|
|
} else if r.Header.Get("X-Original-Host") != "" {
|
|
|
|
domain = r.Header.Get("X-Original-Host")
|
|
|
|
}
|
|
|
|
r.Host = domain
|
|
|
|
r.URL.Host = domain
|
|
|
|
for header, value := range map[string][]string(r.Header) {
|
|
|
|
log.Trace().Strs(header, value).Msg("Headers")
|
|
|
|
}
|
2021-01-23 10:14:33 +00:00
|
|
|
if router, found := s.mrouter[domain]; found {
|
2021-01-24 15:25:58 +00:00
|
|
|
router.NoMethod(gin.WrapH(s.NotFoundHandler))
|
|
|
|
router.NoRoute(gin.WrapH(s.NotFoundHandler))
|
|
|
|
router.ServeHTTP(w, r)
|
2021-01-23 10:14:33 +00:00
|
|
|
return
|
|
|
|
}
|
2021-11-07 17:51:39 +00:00
|
|
|
log.Error().Msgf("Failed to find domain for %s", domain)
|
2021-01-24 15:25:58 +00:00
|
|
|
var entrys []string
|
|
|
|
for d := range s.mrouter {
|
|
|
|
entrys = append(entrys, d)
|
|
|
|
}
|
2021-11-07 17:51:39 +00:00
|
|
|
log.Trace().Strs("registred domains", entrys).Msg("domain not found")
|
2021-01-24 15:25:58 +00:00
|
|
|
s.NotFoundHandler.ServeHTTP(w, r)
|
2021-01-23 10:14:33 +00:00
|
|
|
}
|
|
|
|
|
2021-01-09 20:39:05 +00:00
|
|
|
// Use installs the middleware into the router.
|
|
|
|
// The Middleware must be able to detect multiple calls byy itself. Deduplication is not performed.
|
2021-01-10 14:14:47 +00:00
|
|
|
func (s *Server) Use(m ...gin.HandlerFunc) {
|
2021-11-07 17:51:39 +00:00
|
|
|
s.middleware = append(s.middleware, m...)
|
|
|
|
for _, site := range s.mrouter {
|
|
|
|
site.Use(m...)
|
2021-01-24 15:25:58 +00:00
|
|
|
}
|
2021-01-09 20:39:05 +00:00
|
|
|
}
|
|
|
|
|
2021-01-11 21:39:33 +00:00
|
|
|
// Stop Shuts the Server down
|
2021-01-11 21:45:01 +00:00
|
|
|
func (s *Server) Stop(ctx context.Context) {
|
2021-01-12 18:29:25 +00:00
|
|
|
log.Info().Err(s.http.Shutdown(ctx)).Msg("Server Shut down.")
|
2021-11-06 12:42:07 +00:00
|
|
|
for _, s := range s.sites {
|
2022-11-04 22:49:35 +00:00
|
|
|
if ts, ok := s.(TeardownSite); ok {
|
|
|
|
ts.Teardown()
|
|
|
|
}
|
2021-01-16 18:06:47 +00:00
|
|
|
}
|
2021-01-11 21:39:33 +00:00
|
|
|
}
|
|
|
|
|
2021-01-24 15:25:58 +00:00
|
|
|
func (s *Server) menus() []menus.Menu {
|
|
|
|
return s.menu
|
|
|
|
}
|
|
|
|
|
2022-11-06 09:52:24 +00:00
|
|
|
func maptoarray(m map[string]Site) (a []any) {
|
2021-11-11 22:05:07 +00:00
|
|
|
for _, i := range m {
|
|
|
|
a = append(a, i)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-11-07 17:51:39 +00:00
|
|
|
// Setup sets the server up. It loads the sites and prepare the server for startup.
|
2021-11-11 22:05:07 +00:00
|
|
|
// The Midleware and the site are setup in this Order:
|
|
|
|
// 1. Middleware.Setup
|
|
|
|
// 2. Site.Init
|
|
|
|
// 3. Middleware.Sites
|
|
|
|
// 4. Site.Setup
|
2021-11-06 19:59:56 +00:00
|
|
|
func (s *Server) Setup() {
|
2021-11-10 18:05:52 +00:00
|
|
|
log.Info().Msg("Perparing server for start")
|
2021-11-11 22:05:07 +00:00
|
|
|
var (
|
|
|
|
router *gin.Engine
|
|
|
|
found bool
|
|
|
|
site Site
|
|
|
|
cfg string
|
|
|
|
)
|
2022-11-07 17:45:04 +00:00
|
|
|
for cfg, m := range s.advmiddleware {
|
|
|
|
m.Setup(s.Conf.Middleware[cfg])
|
2021-11-11 22:05:07 +00:00
|
|
|
}
|
|
|
|
for cfg, site = range s.sites {
|
2021-11-06 19:59:56 +00:00
|
|
|
config := s.Conf.Sites[cfg]
|
2021-11-07 17:51:39 +00:00
|
|
|
if router, found = s.mrouter[config["domain"].(string)]; !found {
|
2021-11-10 18:05:52 +00:00
|
|
|
log.Info().Msgf("Setting up router for %s", config["domain"].(string))
|
2021-11-06 19:59:56 +00:00
|
|
|
router = gin.New()
|
2021-11-07 17:51:39 +00:00
|
|
|
router.Use(func(c *gin.Context) {
|
2021-11-11 22:05:07 +00:00
|
|
|
c.Set(constants.Domain, config["domain"])
|
|
|
|
c.Set(constants.Menus, s.menus)
|
|
|
|
c.Set(constants.Accounts, s.authh.Account(c))
|
2021-11-07 17:51:39 +00:00
|
|
|
})
|
|
|
|
router.Use(s.middleware...)
|
2021-11-10 18:05:52 +00:00
|
|
|
router.HTMLRender = templates.NewPongo2Renderer(s.template)
|
2021-11-07 17:51:39 +00:00
|
|
|
s.mrouter[config["domain"].(string)] = router
|
2021-01-24 15:25:58 +00:00
|
|
|
}
|
2021-11-07 17:51:39 +00:00
|
|
|
group := router.Group(config["path"].(string))
|
|
|
|
site.Init(group)
|
2021-11-11 22:06:48 +00:00
|
|
|
}
|
2022-11-07 17:45:04 +00:00
|
|
|
for _, m := range s.advmiddleware {
|
|
|
|
if psm, ok := m.(middleware.PreSetupMiddleware); ok {
|
|
|
|
if err := psm.PreSetup(maptoarray(s.sites)); err != nil {
|
|
|
|
log.Error().Err(err).Msg("Failed to setup midddleware (pre-site-setup). Stopping with the setup")
|
|
|
|
return
|
|
|
|
}
|
2021-11-11 22:18:16 +00:00
|
|
|
}
|
2021-11-11 22:06:48 +00:00
|
|
|
}
|
|
|
|
for cfg, site = range s.sites {
|
|
|
|
config := s.Conf.Sites[cfg]
|
2021-11-06 19:59:56 +00:00
|
|
|
if ms, ok := site.(menus.MenuSite); ok {
|
2021-11-07 17:51:39 +00:00
|
|
|
menus := ms.Menu(config["domain"].(string))
|
2021-11-06 19:59:56 +00:00
|
|
|
log.Debug().Msgf("%d menus are added", len(menus))
|
|
|
|
s.menu = append(s.menu, menus...)
|
2021-01-24 15:25:58 +00:00
|
|
|
}
|
2021-11-06 19:59:56 +00:00
|
|
|
if ts, ok := site.(templates.TemplateSite); ok {
|
|
|
|
templates := ts.Templates()
|
2021-11-10 18:05:52 +00:00
|
|
|
if templates == nil {
|
|
|
|
log.Error().Msgf("Site %s had an empty templateloader", cfg)
|
2021-11-11 22:06:48 +00:00
|
|
|
} else {
|
|
|
|
s.template.AddLoader(templates)
|
2021-11-10 18:05:52 +00:00
|
|
|
}
|
2021-11-06 19:59:56 +00:00
|
|
|
}
|
2022-11-04 22:49:35 +00:00
|
|
|
if cs, ok := site.(ConfigSite); ok {
|
|
|
|
cs.Setup(config)
|
|
|
|
}
|
2021-11-06 19:59:56 +00:00
|
|
|
}
|
2022-11-07 17:45:04 +00:00
|
|
|
for _, m := range s.advmiddleware {
|
|
|
|
if psm, ok := m.(middleware.PostSetupMiddleware); ok {
|
|
|
|
if err := psm.PostSetup(maptoarray(s.sites)); err != nil {
|
|
|
|
log.Error().Err(err).Msg("Failed to setup midddleware (post-site-setup). Stopping with the setup")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-11-06 19:59:56 +00:00
|
|
|
s.setup = true
|
|
|
|
}
|
|
|
|
|
|
|
|
// RegisterSite adds an site to the engine as its own grouo
|
|
|
|
// it registers the defaults so that the application can load/dump it from/into an configfile or commandline options
|
|
|
|
func (s *Server) RegisterSite(cfg string, site Site) {
|
2022-11-04 22:49:35 +00:00
|
|
|
if cs, ok := site.(ConfigSite); ok {
|
|
|
|
var config = cs.Defaults()
|
|
|
|
if _, found := config["domain"]; !found {
|
|
|
|
config["domain"] = ""
|
|
|
|
}
|
|
|
|
if _, found := config["path"]; !found {
|
|
|
|
config["path"] = ""
|
|
|
|
}
|
|
|
|
s.Conf.Sites[cfg] = config
|
2021-11-07 17:51:39 +00:00
|
|
|
}
|
2021-11-06 19:59:56 +00:00
|
|
|
s.sites[cfg] = site
|
2021-01-09 20:39:05 +00:00
|
|
|
}
|
2021-11-11 22:06:48 +00:00
|
|
|
|
|
|
|
// RegisterMiddleware registers middleware that has avanced functions, like persistence.
|
|
|
|
// That middleware allows configuration with the Setup Method and the Teardown allows an safe method for closing connections and shutting down.
|
|
|
|
// Middleware will be set up before sites.
|
|
|
|
func (s *Server) RegisterMiddleware(cfg string, m middleware.Middleware) {
|
|
|
|
s.Conf.Middleware[cfg] = m.Defaults()
|
|
|
|
s.Use(m.Gin)
|
|
|
|
s.advmiddleware[cfg] = m
|
|
|
|
}
|