Files
inventory-plus-plus/internal/site/templates.go
T

219 lines
5.2 KiB
Go

package site
import (
"bytes"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"ruben/inventory2/internal/site/response"
"strings"
)
// GET /
func (s *Server) serveTemplates(r *http.Request) (response.Response, error) {
ctx := r.Context()
name, pathParams := getPageTemplateNameForURL(r.URL)
templateArgs := []any{
"Request",
r,
// add services and data here
"RawEvents",
s.rawEvents.WithContext(ctx),
"URLCalc",
newURLCalculator(r.URL),
"PathParams",
pathParams,
"Accounts",
s.accts.WithContext(ctx),
"Etsy",
s.etsy.WithContext(ctx),
// TODO: apply auth to all templates needed!
// auth tooling
/*
AccessToken string
Claims authentication.AccessTokenClaims
User accounts.OAuthUser
Account *accounts.Account
*/
"Identity",
getIdentity(r.Context()),
"Auth",
newTemplateAuthenticator(r),
}
b, err := s.templater.ExecutePage(name, templateArgs...)
if err != nil {
return s.handleTemplateError(err, templateArgs...)
}
return response.Body(io.NopCloser(bytes.NewBuffer(b))), nil
}
// TODO: clean this up...
// TODO: somehow tell what the path params are and pass them up.
// - then consider pushing this functionality into the template library.
//
// getPageTemplateNameForURL eliminate any trailing .html or /, and checks for any
// file with path parameters in the name, eg '{abc}.html.tmpl', prefering exact filename matches.
func getPageTemplateNameForURL(u *url.URL) (name string, params map[string]string) {
fp := strings.TrimPrefix(strings.TrimSuffix(strings.TrimSuffix(u.Path, ".html"), "/"), "/")
if fp == "" {
// "/" maps to "/index"
fp = "index"
}
fpParts := strings.Split(fp, "/")
res := getMatchingGlobPatternsCapturingFilepathIncludingParametrizedFilepaths(fpParts)
for _, combs := range res {
const pageBodiesPrefix = "internal/site/templates/page_bodies"
pattern := path.Join(pageBodiesPrefix, path.Join(combs...)) + ".html.tmpl"
matches, _ := filepath.Glob(pattern)
if len(matches) == 0 {
pattern := path.Join(pageBodiesPrefix, path.Join(combs...), "index") + ".html.tmpl"
matches, _ = filepath.Glob(pattern)
}
if len(matches) > 0 {
match := matches[0]
name = strings.TrimPrefix(strings.TrimSuffix(match, ".html.tmpl"), pageBodiesPrefix+"/")
patternParts := strings.Split(name, "/")
params = make(map[string]string)
for i, pp := range patternParts {
if strings.HasPrefix(pp, "{") && strings.HasSuffix(pp, "}") {
params[pp[1:len(pp)-1]] = fpParts[i]
}
}
return name, params
}
}
return fp, nil
}
func getMatchingGlobPatternsCapturingFilepathIncludingParametrizedFilepaths(filepathParts []string) [][]string {
switch len(filepathParts) {
case 0:
return nil
case 1:
return [][]string{
[]string{filepathParts[0]},
[]string{"{*}"},
}
default:
tailCombs := getMatchingGlobPatternsCapturingFilepathIncludingParametrizedFilepaths(filepathParts[1:])
combs := make([][]string, 2*len(tailCombs))
for i, c := range tailCombs {
combs[i*2] = append([]string{filepathParts[0]}, c...)
combs[i*2+1] = append([]string{"{*}"}, c...)
}
return combs
}
}
func (s *Server) handleTemplateError(err error, templateArgs ...any) (response.Response, error) {
code := getHTTPStatusCode(err)
if code == http.StatusNotFound ||
code == http.StatusForbidden ||
code == http.StatusUnauthorized ||
isFileNotFoundError(err) {
b, err := s.templater.ExecutePage("not-found", templateArgs...)
if err != nil {
fmt.Println("failed to render not found page:", err)
return nil, response.NotFound().
Wrap(err).
Msg("resource not found")
}
return response.Body(io.NopCloser(bytes.NewBuffer(b))), nil
}
if code == http.StatusConflict {
b, err := s.templater.ExecutePage("conflict", templateArgs...)
if err != nil {
fmt.Println("failed to render conflict page:", err)
return nil, response.Conflict().
Wrap(err).
Msg("conflict")
}
return response.Body(io.NopCloser(bytes.NewBuffer(b))), nil
}
return nil, fmt.Errorf("failed to render page: %w", err)
}
func isFileNotFoundError(err error) bool {
var pe *os.PathError
isPathErr := errors.As(err, &pe)
return isPathErr && pe.Err != nil && pe.Err.Error() == "no such file or directory"
}
func getHTTPStatusCode(err error) int {
rerr, ok := response.GetError(err)
if !ok {
return http.StatusInternalServerError
}
code, ok := rerr.GetStatus()
if !ok {
return http.StatusInternalServerError
}
return code
}
// template tooling
type URLCalculator struct {
url *url.URL
}
func newURLCalculator(u *url.URL) URLCalculator {
cpy := *u
return URLCalculator{
url: &cpy,
}
}
func (c URLCalculator) SetQueryParam(k string, v any) string {
u := *c.url
q := u.Query()
q.Set(k, fmt.Sprint(v))
u.RawQuery = q.Encode()
return u.String()
}
// template authenticator
type templateAuthenticator struct {
req *http.Request
}
func newTemplateAuthenticator(req *http.Request) *templateAuthenticator {
return &templateAuthenticator{
req: req,
}
}
// templateAuthorizationFunc these shouild always return an empty string
type templateAuthorizationFunc = func() (string, error)
func (a *templateAuthenticator) ByMatchingAccountID(acctIDPathPosition int) (string, error) {
return "", authorizeByMatchingAccountID(a.req, acctIDPathPosition)
}