simplified NewServer()

This commit is contained in:
2026-01-12 05:03:05 -07:00
parent 0d6af06d65
commit 1001be08e9
+82 -107
View File
@@ -27,18 +27,6 @@ import (
etsy_webhooks "ruben/inventory2/internal/server/webhooks/etsy" etsy_webhooks "ruben/inventory2/internal/server/webhooks/etsy"
) )
type Server struct {
log *slog.Logger
*router.Mux
contentDir string
templater *templater.Templater
rawEvents *raw_events.Store
accts *accounts.Store
etsy *etsy_platform.Platform
auth *authentication.Authenticator
authMiddleware *middleware.Auth
}
func NewServer( func NewServer(
ctx context.Context, ctx context.Context,
logger *slog.Logger, logger *slog.Logger,
@@ -47,91 +35,95 @@ func NewServer(
accts *accounts.Store, accts *accounts.Store,
etsy *etsy_platform.Platform, etsy *etsy_platform.Platform,
auth *authentication.Authenticator, auth *authentication.Authenticator,
) *Server { ) http.Handler {
mux := router.NewMux( mux := router.NewMux(
logger, logger,
middleware.LogRequests(ctx, logger.WithGroup("request")), middleware.LogRequests(ctx, logger.WithGroup("request")),
) )
tmpl := templater.NewTemplater( // TODO: shouldn't this ACTUALLY be a middleware?
contentDir+"/templates", // - only try to make this an actual middleware AFTER all the routers are broken out, so that way how the middleware is supposed to work can be known
func() template.FuncMap { authMiddleware := middleware.NewAuth(
return template.FuncMap{ logger.WithGroup("auth-middleware"),
// params auth,
"addPathParam": func(k string, v any, args map[string]any) (map[string]any, error) { auth_api.NewLoginURL,
pathParams, ok := args["PathParams"].(map[string]string) accts,
if !ok {
return nil, fmt.Errorf("PathParams no set are args: %v", args)
}
pathParams[k] = fmt.Sprint(v)
return args, nil
},
// parsing
"parseInt": func(s string) (int, error) {
return strconv.Atoi(s)
},
"parseInt64": func(s string) (int64, error) {
return strconv.ParseInt(s, 10, 64)
},
"parsePlatform": func(s string) (accounts.Platform, error) {
return accounts.NewPlatform(s)
},
// arithmetic
"addInt": func(a, b int) int {
return a + b
},
"subInt": func(a, b int) int {
return a - b
},
"multInt": func(a, b int) int {
return a * b
},
// json
"prettyPrintJSON": func(j json.RawMessage) string {
b, err := json.MarshalIndent(j, " ", "")
if err != nil {
return string(j)
}
return string(b)
},
}
},
) )
s := &Server{ // webpage content
// TODO: eliminate fields that aren't needed anymore
log: logger, // non-html content: scripts, styles, images, etc
Mux: mux,
contentDir: contentDir, scfs := http.FileServer(http.Dir(contentDir + "/scripts"))
templater: tmpl, mux.Mux.Handle("GET /scripts/", http.StripPrefix("/scripts", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rawEvents: rawEvents, w.Header().Set("Content-Type", "text/javascript")
accts: accts, if path.Ext(r.URL.Path) == ".gz" {
etsy: etsy, w.Header().Set("Content-Encoding", "gzip")
auth: auth, }
// TODO: shouldn't this ACTUALLY be a middleware? scfs.ServeHTTP(w, r)
// - only try to make this an actual middleware AFTER all the routers are broken out, so that way how the middleware is supposed to work can be known })))
authMiddleware: middleware.NewAuth( mux.Mux.Handle("GET /styles/", http.StripPrefix("/styles", http.FileServer(http.Dir(contentDir+"/styles"))))
logger.WithGroup("auth-middleware"), mux.Mux.Handle("GET /favicon/", http.StripPrefix("/favicon", http.FileServer(http.Dir(contentDir+"/favicon"))))
auth,
auth_api.NewLoginURL, // html (must be before the api endpoints, because the webpage middleware has to be installed beforehand
accts,
),
}
// kind of a dumb way to capture routes for webpages // kind of a dumb way to capture routes for webpages
wpr := templates_api.NewWebpageRouter( wpr := templates_api.NewWebpageRouter(
s.log.WithGroup("templates"), logger.WithGroup("templates"),
contentDir, contentDir,
tmpl, templater.NewTemplater(
contentDir+"/templates",
func() template.FuncMap {
return template.FuncMap{
// params
"addPathParam": func(k string, v any, args map[string]any) (map[string]any, error) {
pathParams, ok := args["PathParams"].(map[string]string)
if !ok {
return nil, fmt.Errorf("PathParams no set are args: %v", args)
}
pathParams[k] = fmt.Sprint(v)
return args, nil
},
// parsing
"parseInt": func(s string) (int, error) {
return strconv.Atoi(s)
},
"parseInt64": func(s string) (int64, error) {
return strconv.ParseInt(s, 10, 64)
},
"parsePlatform": func(s string) (accounts.Platform, error) {
return accounts.NewPlatform(s)
},
// arithmetic
"addInt": func(a, b int) int {
return a + b
},
"subInt": func(a, b int) int {
return a - b
},
"multInt": func(a, b int) int {
return a * b
},
// json
"prettyPrintJSON": func(j json.RawMessage) string {
b, err := json.MarshalIndent(j, " ", "")
if err != nil {
return string(j)
}
return string(b)
},
}
},
),
rawEvents, rawEvents,
accts, accts,
etsy, etsy,
s.authMiddleware, authMiddleware,
) )
mux.AddMiddleware( mux.AddMiddleware(
func(fn response.HandlerFunc) response.HandlerFunc { func(fn response.HandlerFunc) response.HandlerFunc {
@@ -155,13 +147,15 @@ func NewServer(
}, },
) )
mux.Route("/", wpr)
// api endpoints // api endpoints
mux.Route("/auth", auth_api.NewLoginSubrouter(s.log.WithGroup("/auth"), auth)) mux.Route("/auth", auth_api.NewLoginSubrouter(logger.WithGroup("/auth"), auth))
mux.Route("/accounts", accounts_api.NewAccountSubrouter( mux.Route("/accounts", accounts_api.NewAccountSubrouter(
s.log.WithGroup("/accounts"), logger.WithGroup("/accounts"),
s.accts, accts,
s.authMiddleware, authMiddleware,
)) ))
// api webhooks (TODO: make a router for these) // api webhooks (TODO: make a router for these)
@@ -180,24 +174,5 @@ func NewServer(
mux.Mux.Handle("POST /webhooks/", webhookHandler) mux.Mux.Handle("POST /webhooks/", webhookHandler)
mux.Mux.Handle("PUT /webhooks/", webhookHandler) mux.Mux.Handle("PUT /webhooks/", webhookHandler)
// webpage content return mux
// non-html content: scripts, styles, images, etc
scfs := http.FileServer(http.Dir(contentDir + "/scripts"))
mux.Mux.Handle("GET /scripts/", http.StripPrefix("/scripts", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/javascript")
if path.Ext(r.URL.Path) == ".gz" {
w.Header().Set("Content-Encoding", "gzip")
}
scfs.ServeHTTP(w, r)
})))
mux.Mux.Handle("GET /styles/", http.StripPrefix("/styles", http.FileServer(http.Dir(contentDir+"/styles"))))
mux.Mux.Handle("GET /favicon/", http.StripPrefix("/favicon", http.FileServer(http.Dir(contentDir+"/favicon"))))
// html
mux.Route("/", wpr)
return s
} }