diff options
Diffstat (limited to 'internal')
-rw-r--r-- | internal/atom/atom.go | 40 | ||||
-rw-r--r-- | internal/builder/builder.go | 88 | ||||
-rw-r--r-- | internal/builder/template.go | 110 | ||||
-rw-r--r-- | internal/config/config.go | 14 | ||||
-rw-r--r-- | internal/config/cspgenerator.go | 2 | ||||
-rw-r--r-- | internal/content/posts.go | 19 | ||||
-rw-r--r-- | internal/listenfd/listenfd.go | 33 | ||||
-rw-r--r-- | internal/log/log.go | 63 | ||||
-rw-r--r-- | internal/server/dev.go | 24 | ||||
-rw-r--r-- | internal/server/logging.go | 11 | ||||
-rw-r--r-- | internal/server/mime.go | 9 | ||||
-rw-r--r-- | internal/server/server.go | 140 | ||||
-rw-r--r-- | internal/server/tcp.go | 19 | ||||
-rw-r--r-- | internal/server/tls.go | 148 | ||||
-rw-r--r-- | internal/sitemap/sitemap.go | 7 | ||||
-rw-r--r-- | internal/vcs/repository.go | 44 | ||||
-rw-r--r-- | internal/website/filemap.go | 6 | ||||
-rw-r--r-- | internal/website/mux.go | 33 |
18 files changed, 430 insertions, 380 deletions
diff --git a/internal/atom/atom.go b/internal/atom/atom.go index a5965a4..f75d18a 100644 --- a/internal/atom/atom.go +++ b/internal/atom/atom.go @@ -1,28 +1,47 @@ package atom import ( + "bytes" "encoding/xml" + "net/url" "time" - "website/internal/config" + "go.alanpearce.eu/website/internal/config" ) -func MakeTagURI(config config.Config, specific string) string { +func MakeTagURI(config *config.Config, specific string) string { return "tag:" + config.OriginalDomain + "," + config.DomainStartDate + ":" + specific } +func LinkXSL(w *bytes.Buffer, url string) error { + _, err := w.WriteString(`<?xml-stylesheet href="`) + if err != nil { + return err + } + err = xml.EscapeText(w, []byte(url)) + if err != nil { + return err + } + _, err = w.WriteString(`" type="text/xsl"?>`) + if err != nil { + return err + } + + return nil +} + type Link struct { XMLName xml.Name `xml:"link"` - Rel string `xml:"rel,attr"` - Type string `xml:"type,attr"` + Rel string `xml:"rel,attr,omitempty"` + Type string `xml:"type,attr,omitempty"` Href string `xml:"href,attr"` } -func MakeLink(url string) Link { +func MakeLink(url *url.URL) Link { return Link{ Rel: "alternate", Type: "text/html", - Href: url, + Href: url.String(), } } @@ -41,3 +60,12 @@ type FeedEntry struct { Content FeedContent `xml:"content"` Author string `xml:"author>name"` } + +type Feed struct { + XMLName xml.Name `xml:"http://www.w3.org/2005/Atom feed"` + Title string `xml:"title"` + Link Link `xml:"link"` + ID string `xml:"id"` + Updated time.Time `xml:"updated"` + Entries []*FeedEntry `xml:"entry"` +} diff --git a/internal/builder/builder.go b/internal/builder/builder.go index 4436151..b99d919 100644 --- a/internal/builder/builder.go +++ b/internal/builder/builder.go @@ -6,23 +6,24 @@ import ( "io" "os" "path" + "path/filepath" "slices" "time" - "website/internal/config" - "website/internal/content" - "website/internal/log" - "website/internal/sitemap" - "website/templates" + "go.alanpearce.eu/website/internal/config" + "go.alanpearce.eu/website/internal/content" + "go.alanpearce.eu/x/log" + "go.alanpearce.eu/website/internal/sitemap" + "go.alanpearce.eu/website/templates" "github.com/a-h/templ" mapset "github.com/deckarep/golang-set/v2" - "github.com/pkg/errors" + "gitlab.com/tozd/go/errors" ) type IOConfig struct { Source string `conf:"default:.,short:s,flag:src"` - Destination string `conf:"default:website,short:d,flag:dest"` + Destination string `conf:"default:public,short:d,flag:dest"` Development bool `conf:"default:false,flag:dev"` } @@ -86,30 +87,34 @@ func writerToFile(writer io.WriterTo, pathParts ...string) error { return nil } -func build(outDir string, config config.Config) (*Result, error) { +func joinSourcePath(src string) func(string) string { + return func(rel string) string { + return filepath.Join(src, rel) + } +} + +func build(ioConfig *IOConfig, config *config.Config, log *log.Logger) (*Result, error) { + outDir := ioConfig.Destination + joinSource := joinSourcePath(ioConfig.Source) log.Debug("output", "dir", outDir) r := &Result{ Hashes: make([]string, 0), } - privateDir := path.Join(outDir, "private") - if err := mkdirp(privateDir); err != nil { - return nil, errors.WithMessage(err, "could not create private directory") - } - publicDir := path.Join(outDir, "public") - if err := mkdirp(publicDir); err != nil { - return nil, errors.WithMessage(err, "could not create public directory") - } - err := copyRecursive("static", publicDir) + err := copyRecursive(joinSource("static"), outDir) if err != nil { return nil, errors.WithMessage(err, "could not copy static files") } - if err := mkdirp(publicDir, "post"); err != nil { + if err := mkdirp(outDir, "post"); err != nil { return nil, errors.WithMessage(err, "could not create post output directory") } log.Debug("reading posts") - posts, tags, err := content.ReadPosts("content", "post", publicDir) + posts, tags, err := content.ReadPosts(&content.Config{ + Root: joinSource("content"), + InputDir: "post", + OutputDir: outDir, + }, log.Named("content")) if err != nil { return nil, err } @@ -121,7 +126,7 @@ func build(outDir string, config config.Config) (*Result, error) { } for _, post := range posts { - if err := mkdirp(publicDir, "post", post.Basename); err != nil { + if err := mkdirp(outDir, "post", post.Basename); err != nil { return nil, errors.WithMessage(err, "could not create directory for post") } log.Debug("rendering post", "post", post.Basename) @@ -131,13 +136,13 @@ func build(outDir string, config config.Config) (*Result, error) { } } - if err := mkdirp(publicDir, "tags"); err != nil { + if err := mkdirp(outDir, "tags"); err != nil { return nil, errors.WithMessage(err, "could not create directory for tags") } log.Debug("rendering tags list") if err := renderToFile( templates.TagsPage(config, "tags", mapset.Sorted(tags), "/tags"), - publicDir, + outDir, "tags", "index.html", ); err != nil { @@ -152,14 +157,14 @@ func build(outDir string, config config.Config) (*Result, error) { matchingPosts = append(matchingPosts, post) } } - if err := mkdirp(publicDir, "tags", tag); err != nil { + if err := mkdirp(outDir, "tags", tag); err != nil { return nil, errors.WithMessage(err, "could not create directory") } log.Debug("rendering tags page", "tag", tag) url := "/tags/" + tag if err := renderToFile( templates.TagPage(config, tag, matchingPosts, url), - publicDir, + outDir, "tags", tag, "index.html", @@ -178,13 +183,13 @@ func build(outDir string, config config.Config) (*Result, error) { if err != nil { return nil, errors.WithMessage(err, "could not render tag feed page") } - if err := outputToFile(feed, publicDir, "tags", tag, "atom.xml"); err != nil { + if err := writerToFile(feed, outDir, "tags", tag, "atom.xml"); err != nil { return nil, err } } log.Debug("rendering list page") - if err := renderToFile(templates.ListPage(config, posts, "/post"), publicDir, "post", "index.html"); err != nil { + if err := renderToFile(templates.ListPage(config, posts, "/post"), outDir, "post", "index.html"); err != nil { return nil, err } sitemap.AddPath("/post/", lastMod) @@ -194,16 +199,16 @@ func build(outDir string, config config.Config) (*Result, error) { if err != nil { return nil, errors.WithMessage(err, "could not render feed") } - if err := outputToFile(feed, publicDir, "atom.xml"); err != nil { + if err := writerToFile(feed, outDir, "atom.xml"); err != nil { return nil, err } log.Debug("rendering feed styles") - feedStyles, err := renderFeedStyles() + feedStyles, err := renderFeedStyles(ioConfig.Source) if err != nil { return nil, errors.WithMessage(err, "could not render feed styles") } - if err := outputToFile(feedStyles, publicDir, "feed-styles.xsl"); err != nil { + if err := outputToFile(feedStyles, outDir, "feed-styles.xsl"); err != nil { return nil, err } _, err = feedStyles.Seek(0, 0) @@ -217,7 +222,7 @@ func build(outDir string, config config.Config) (*Result, error) { r.Hashes = append(r.Hashes, h) log.Debug("rendering homepage") - _, text, err := content.GetPost(path.Join("content", "index.md")) + _, text, err := content.GetPost(joinSource(filepath.Join("content", "index.md"))) if err != nil { return nil, err } @@ -225,43 +230,42 @@ func build(outDir string, config config.Config) (*Result, error) { if err != nil { return nil, err } - if err := renderToFile(templates.Homepage(config, posts, content), publicDir, "index.html"); err != nil { + if err := renderToFile(templates.Homepage(config, posts, content), outDir, "index.html"); err != nil { return nil, err } // it would be nice to set LastMod here, but using the latest post // date would be wrong as the homepage has its own content file // without a date, which could be newer sitemap.AddPath("/", time.Time{}) - h, _ = getHTMLStyleHash(publicDir, "index.html") + h, _ = getHTMLStyleHash(outDir, "index.html") r.Hashes = append(r.Hashes, h) log.Debug("rendering sitemap") - if err := writerToFile(sitemap, publicDir, "sitemap.xml"); err != nil { + if err := writerToFile(sitemap, outDir, "sitemap.xml"); err != nil { return nil, err } log.Debug("rendering robots.txt") - rob, err := renderRobotsTXT(config) + rob, err := renderRobotsTXT(ioConfig.Source, config) if err != nil { return nil, err } - if err := outputToFile(rob, publicDir, "robots.txt"); err != nil { + if err := outputToFile(rob, outDir, "robots.txt"); err != nil { return nil, err } return r, nil } -func BuildSite(ioConfig IOConfig) (*Result, error) { - config, err := config.GetConfig() - if err != nil { - return nil, errors.WithMessage(err, "could not get config") +func BuildSite(ioConfig *IOConfig, cfg *config.Config, log *log.Logger) (*Result, error) { + if cfg == nil { + return nil, errors.New("config is nil") } - config.InjectLiveReload = ioConfig.Development + cfg.InjectLiveReload = ioConfig.Development compressFiles = !ioConfig.Development templates.Setup() - loadCSS() + loadCSS(ioConfig.Source) - return build(ioConfig.Destination, *config) + return build(ioConfig, cfg, log) } diff --git a/internal/builder/template.go b/internal/builder/template.go index da45fb7..9f019df 100644 --- a/internal/builder/template.go +++ b/internal/builder/template.go @@ -1,53 +1,41 @@ package builder import ( + "bytes" "encoding/xml" "io" "os" "path/filepath" "strings" "text/template" - "website/internal/atom" - "website/internal/config" - "website/internal/content" + + "go.alanpearce.eu/website/internal/atom" + "go.alanpearce.eu/website/internal/config" + "go.alanpearce.eu/website/internal/content" "github.com/PuerkitoBio/goquery" "github.com/antchfx/xmlquery" "github.com/antchfx/xpath" - "github.com/pkg/errors" + "gitlab.com/tozd/go/errors" ) var ( - css string - templateFiles = make(map[string]*os.File) - nsMap = map[string]string{ + css string + nsMap = map[string]string{ "xsl": "http://www.w3.org/1999/XSL/Transform", "atom": "http://www.w3.org/2005/Atom", "xhtml": "http://www.w3.org/1999/xhtml", } ) -func loadCSS() { - bytes, err := os.ReadFile("templates/style.css") +func loadCSS(source string) { + bytes, err := os.ReadFile(filepath.Join(source, "templates/style.css")) if err != nil { panic(err) } css = string(bytes) } -func loadTemplate(path string) (file *os.File, err error) { - if templateFiles[path] == nil { - file, err = os.OpenFile(path, os.O_RDONLY, 0) - if err != nil { - return nil, errors.Wrapf(err, "could not load template at path %s", path) - } - templateFiles[path] = file - } - file = templateFiles[path] - - return -} - type QuerySelection struct { *goquery.Selection } @@ -66,9 +54,9 @@ func (q *QueryDocument) Find(selector string) *QuerySelection { return &QuerySelection{q.Document.Find(selector)} } -func renderRobotsTXT(config config.Config) (io.Reader, error) { +func renderRobotsTXT(source string, config *config.Config) (io.Reader, error) { r, w := io.Pipe() - tpl, err := template.ParseFiles("templates/robots.tmpl") + tpl, err := template.ParseFiles(filepath.Join(source, "templates/robots.tmpl")) if err != nil { return nil, err } @@ -87,41 +75,30 @@ func renderRobotsTXT(config config.Config) (io.Reader, error) { func renderFeed( title string, - config config.Config, + config *config.Config, posts []content.Post, specific string, -) (io.Reader, error) { - reader, err := loadTemplate("templates/feed.xml") +) (io.WriterTo, error) { + buf := &bytes.Buffer{} + datetime := posts[0].Date.UTC() + + buf.WriteString(xml.Header) + err := atom.LinkXSL(buf, "/feed-styles.xsl") if err != nil { return nil, err } - defer func() { - _, err := reader.Seek(0, io.SeekStart) - if err != nil { - panic("could not reset reader: " + err.Error()) - } - }() - doc, err := xmlquery.Parse(reader) - if err != nil { - return nil, errors.Wrap(err, "could not parse XML") - } - feed := doc.SelectElement("feed") - feed.SelectElement("title").FirstChild.Data = title - feed.SelectElement("link").SetAttr("href", config.BaseURL.String()) - feed.SelectElement("id").FirstChild.Data = atom.MakeTagURI(config, specific) - datetime, err := posts[0].Date.UTC().MarshalText() - if err != nil { - return nil, errors.Wrap(err, "could not convert post date to text") + feed := &atom.Feed{ + Title: title, + Link: atom.MakeLink(config.BaseURL.URL), + ID: atom.MakeTagURI(config, specific), + Updated: datetime, + Entries: make([]*atom.FeedEntry, len(posts)), } - feed.SelectElement("updated").FirstChild.Data = string(datetime) - tpl := feed.SelectElement("entry") - xmlquery.RemoveFromTree(tpl) - for _, post := range posts { - fullURL := config.BaseURL.JoinPath(post.URL).String() - text, err := xml.MarshalIndent(&atom.FeedEntry{ + for i, post := range posts { + feed.Entries[i] = &atom.FeedEntry{ Title: post.Title, - Link: atom.MakeLink(fullURL), + Link: atom.MakeLink(config.BaseURL.JoinPath(post.URL)), ID: atom.MakeTagURI(config, post.Basename), Updated: post.Date.UTC(), Summary: post.Description, @@ -130,31 +107,19 @@ func renderFeed( Content: post.Content, Type: "html", }, - }, " ", " ") - if err != nil { - return nil, errors.Wrap(err, "could not marshal xml") - } - entry, err := xmlquery.ParseWithOptions( - strings.NewReader(string(text)), - xmlquery.ParserOptions{ - Decoder: &xmlquery.DecoderOptions{ - Strict: false, - AutoClose: xml.HTMLAutoClose, - Entity: xml.HTMLEntity, - }, - }, - ) - if err != nil { - return nil, errors.Wrap(err, "could not parse XML") } - xmlquery.AddChild(feed, entry.SelectElement("entry")) + } + enc := xml.NewEncoder(buf) + err = enc.Encode(feed) + if err != nil { + return nil, err } - return strings.NewReader(doc.OutputXML(true)), nil + return buf, nil } -func renderFeedStyles() (*strings.Reader, error) { - tpl, err := template.ParseFiles("templates/feed-styles.xsl") +func renderFeedStyles(source string) (*strings.Reader, error) { + tpl, err := template.ParseFiles(filepath.Join(source, "templates/feed-styles.xsl")) if err != nil { return nil, err } @@ -169,6 +134,9 @@ func renderFeedStyles() (*strings.Reader, error) { err = tpl.Execute(w, map[string]interface{}{ "css": esc.String(), }) + if err != nil { + return nil, err + } return strings.NewReader(w.String()), nil } diff --git a/internal/config/config.go b/internal/config/config.go index 7d43462..47d5de8 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -3,10 +3,12 @@ package config import ( "io/fs" "net/url" - "website/internal/log" + "path/filepath" + + "go.alanpearce.eu/x/log" "github.com/BurntSushi/toml" - "github.com/pkg/errors" + "gitlab.com/tozd/go/errors" ) type Taxonomy struct { @@ -38,6 +40,7 @@ type Config struct { Description string DomainStartDate string `toml:"domain_start_date"` OriginalDomain string `toml:"original_domain"` + GoatCounter URL `toml:"goatcounter"` Domains []string OIDCHost URL `toml:"oidc_host"` Taxonomies []Taxonomy @@ -48,10 +51,11 @@ type Config struct { Menus map[string][]MenuItem } -func GetConfig() (*Config, error) { +func GetConfig(dir string, log *log.Logger) (*Config, error) { config := Config{} - log.Debug("reading config.toml") - _, err := toml.DecodeFile("config.toml", &config) + filename := filepath.Join(dir, "config.toml") + log.Debug("reading config", "filename", filename) + _, err := toml.DecodeFile(filename, &config) if err != nil { switch t := err.(type) { case *fs.PathError: diff --git a/internal/config/cspgenerator.go b/internal/config/cspgenerator.go index 40eca01..9974819 100644 --- a/internal/config/cspgenerator.go +++ b/internal/config/cspgenerator.go @@ -9,7 +9,7 @@ import ( "github.com/crewjam/csp" "github.com/fatih/structtag" - "github.com/pkg/errors" + "gitlab.com/tozd/go/errors" ) func GenerateCSP() error { diff --git a/internal/content/posts.go b/internal/content/posts.go index 5185d06..f4c6c76 100644 --- a/internal/content/posts.go +++ b/internal/content/posts.go @@ -8,15 +8,16 @@ import ( "slices" "strings" "time" - "website/internal/log" + + "go.alanpearce.eu/x/log" "github.com/adrg/frontmatter" mapset "github.com/deckarep/golang-set/v2" - "github.com/pkg/errors" fences "github.com/stefanfritsch/goldmark-fences" "github.com/yuin/goldmark" "github.com/yuin/goldmark/extension" htmlrenderer "github.com/yuin/goldmark/renderer/html" + "gitlab.com/tozd/go/errors" ) type PostMatter struct { @@ -79,16 +80,22 @@ func RenderMarkdown(content []byte) (string, error) { return buf.String(), nil } -func ReadPosts(root string, inputDir string, outputDir string) ([]Post, Tags, error) { +type Config struct { + Root string + InputDir string + OutputDir string +} + +func ReadPosts(config *Config, log *log.Logger) ([]Post, Tags, error) { tags := mapset.NewSet[string]() posts := []Post{} - subdir := filepath.Join(root, inputDir) + subdir := filepath.Join(config.Root, config.InputDir) files, err := os.ReadDir(subdir) if err != nil { return nil, nil, errors.WithMessagef(err, "could not read post directory %s", subdir) } - outputReplacer := strings.NewReplacer(root, outputDir, ".md", "/index.html") - urlReplacer := strings.NewReplacer(root, "", ".md", "/") + outputReplacer := strings.NewReplacer(config.Root, config.OutputDir, ".md", "/index.html") + urlReplacer := strings.NewReplacer(config.Root, "", ".md", "/") for _, f := range files { pathFromRoot := filepath.Join(subdir, f.Name()) if !f.IsDir() && path.Ext(pathFromRoot) == ".md" { diff --git a/internal/listenfd/listenfd.go b/internal/listenfd/listenfd.go deleted file mode 100644 index 7d020b0..0000000 --- a/internal/listenfd/listenfd.go +++ /dev/null @@ -1,33 +0,0 @@ -package listenfd - -import ( - "net" - "os" - "strconv" - - "github.com/pkg/errors" -) - -const fdStart = 3 - -func GetListener(i uint64) (net.Listener, error) { - lfds, present := os.LookupEnv("LISTEN_FDS") - if !present { - return nil, nil - } - - fds, err := strconv.ParseUint(lfds, 10, 32) - if err != nil { - return nil, errors.Wrap(err, "could not parse LISTEN_FDS") - } - if i >= fds { - return nil, errors.Errorf("only %d fds available, requested index %d", fds, i) - } - - l, err := net.FileListener(os.NewFile(uintptr(i+fdStart), "")) - if err != nil { - return nil, errors.Wrap(err, "could not create listener") - } - - return l, nil -} diff --git a/internal/log/log.go b/internal/log/log.go deleted file mode 100644 index a0f5ba7..0000000 --- a/internal/log/log.go +++ /dev/null @@ -1,63 +0,0 @@ -package log - -import ( - "os" - - zaplogfmt "github.com/sykesm/zap-logfmt" - prettyconsole "github.com/thessem/zap-prettyconsole" - "go.uber.org/zap" - "go.uber.org/zap/zapcore" -) - -var logger *zap.SugaredLogger - -func DPanic(msg string, rest ...any) { - logger.DPanicw(msg, rest...) -} -func Debug(msg string, rest ...any) { - logger.Debugw(msg, rest...) -} -func Info(msg string, rest ...any) { - logger.Infow(msg, rest...) -} -func Warn(msg string, rest ...any) { - logger.Warnw(msg, rest...) -} -func Error(msg string, rest ...any) { - logger.Errorw(msg, rest...) -} -func Panic(msg string, rest ...any) { - logger.Panicw(msg, rest...) -} -func Fatal(msg string, rest ...any) { - logger.Fatalw(msg, rest...) -} - -func getLevelFromEnv() (zapcore.Level, error) { - if str, found := os.LookupEnv("LOG_LEVEL"); found { - l, err := zap.ParseAtomicLevel(str) - - return l.Level(), err - } - - return zap.InfoLevel, nil -} - -func Configure(isProduction bool) { - var l *zap.Logger - level, err := getLevelFromEnv() - if err != nil { - panic(err) - } - if isProduction { - cfg := zap.NewProductionEncoderConfig() - cfg.TimeKey = "" - l = zap.New(zapcore.NewCore(zaplogfmt.NewEncoder(cfg), os.Stderr, level)) - } else { - cfg := prettyconsole.NewConfig() - cfg.EncoderConfig.TimeKey = "" - cfg.Level.SetLevel(level) - l = zap.Must(cfg.Build()) - } - logger = l.WithOptions(zap.AddCallerSkip(1)).Sugar() -} diff --git a/internal/server/dev.go b/internal/server/dev.go index aac869d..6fcc93e 100644 --- a/internal/server/dev.go +++ b/internal/server/dev.go @@ -3,16 +3,16 @@ package server import ( "fmt" "io/fs" - "log/slog" "os" "path" "path/filepath" "slices" "time" - "website/internal/log" + + "go.alanpearce.eu/x/log" "github.com/fsnotify/fsnotify" - "github.com/pkg/errors" + "gitlab.com/tozd/go/errors" ) type FileWatcher struct { @@ -20,6 +20,7 @@ type FileWatcher struct { } var ( + l *log.Logger ignores = []string{ "*.templ", "*.go", @@ -31,7 +32,7 @@ func matches(name string) func(string) bool { return func(pattern string) bool { matched, err := path.Match(pattern, name) if err != nil { - log.Warn("error checking watcher ignores", "error", err) + l.Warn("error checking watcher ignores", "error", err) } return matched @@ -42,23 +43,24 @@ func ignored(pathname string) bool { return slices.ContainsFunc(ignores, matches(path.Base(pathname))) } -func NewFileWatcher() (*FileWatcher, error) { +func NewFileWatcher(log *log.Logger) (*FileWatcher, error) { watcher, err := fsnotify.NewWatcher() if err != nil { return nil, errors.WithMessage(err, "could not create watcher") } + l = log return &FileWatcher{watcher}, nil } func (watcher FileWatcher) AddRecursive(from string) error { - log.Debug("walking directory tree", "root", from) + l.Debug("walking directory tree", "root", from) err := filepath.WalkDir(from, func(path string, entry fs.DirEntry, err error) error { if err != nil { return errors.WithMessagef(err, "could not walk directory %s", path) } if entry.IsDir() { - log.Debug("adding directory to watcher", "path", path) + l.Debug("adding directory to watcher", "path", path) if err = watcher.Add(path); err != nil { return errors.WithMessagef(err, "could not add directory %s to watcher", path) } @@ -76,17 +78,17 @@ func (watcher FileWatcher) Start(callback func(string)) { select { case event := <-watcher.Events: if !ignored(event.Name) { - log.Debug("watcher event", "name", event.Name, "op", event.Op.String()) + l.Debug("watcher event", "name", event.Name, "op", event.Op.String()) if event.Has(fsnotify.Create) || event.Has(fsnotify.Rename) { f, err := os.Stat(event.Name) if err != nil { - slog.Error( + l.Error( fmt.Sprintf("error handling %s event: %v", event.Op.String(), err), ) } else if f.IsDir() { err = watcher.Add(event.Name) if err != nil { - slog.Error(fmt.Sprintf("error adding new folder to watcher: %v", err)) + l.Error(fmt.Sprintf("error adding new folder to watcher: %v", err)) } } } @@ -101,7 +103,7 @@ func (watcher FileWatcher) Start(callback func(string)) { } } case err := <-watcher.Errors: - slog.Error(fmt.Sprintf("error in watcher: %v", err)) + l.Error("error in watcher", "error", err) } } } diff --git a/internal/server/logging.go b/internal/server/logging.go index 5d607bb..f744931 100644 --- a/internal/server/logging.go +++ b/internal/server/logging.go @@ -2,7 +2,8 @@ package server import ( "net/http" - "website/internal/log" + + "go.alanpearce.eu/x/log" ) type LoggingResponseWriter struct { @@ -22,20 +23,18 @@ func NewLoggingResponseWriter(w http.ResponseWriter) *LoggingResponseWriter { return &LoggingResponseWriter{w, http.StatusOK} } -func wrapHandlerWithLogging(wrappedHandler http.Handler) http.Handler { +func wrapHandlerWithLogging(wrappedHandler http.Handler, log *log.Logger) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - host := r.Host lw := NewLoggingResponseWriter(w) wrappedHandler.ServeHTTP(lw, r) if r.URL.Path == "/health" { return } - statusCode := lw.statusCode log.Info( "http request", "method", r.Method, - "status", statusCode, - "host", host, + "status", lw.statusCode, + "host", r.Host, "path", r.URL.Path, "location", lw.Header().Get("Location"), ) diff --git a/internal/server/mime.go b/internal/server/mime.go index 696a0ad..cb1b1cf 100644 --- a/internal/server/mime.go +++ b/internal/server/mime.go @@ -2,21 +2,18 @@ package server import ( "mime" - "website/internal/log" + + "go.alanpearce.eu/x/log" ) var newMIMEs = map[string]string{ ".xsl": "text/xsl", } -func fixupMIMETypes() { +func fixupMIMETypes(log *log.Logger) { for ext, newType := range newMIMEs { if err := mime.AddExtensionType(ext, newType); err != nil { log.Error("could not update mime type", "ext", ext, "mime", newType) } } } - -func init() { - fixupMIMETypes() -} diff --git a/internal/server/server.go b/internal/server/server.go index 3110ec0..b174c0c 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -7,21 +7,21 @@ import ( "net/http" "net/url" "os" + "path/filepath" "slices" "strconv" + "strings" "time" - "website/internal/builder" - cfg "website/internal/config" - "website/internal/log" - "website/internal/vcs" - "website/internal/website" + "go.alanpearce.eu/website/internal/builder" + cfg "go.alanpearce.eu/website/internal/config" + "go.alanpearce.eu/website/internal/vcs" + "go.alanpearce.eu/website/internal/website" + "go.alanpearce.eu/x/log" "github.com/ardanlabs/conf/v3" "github.com/osdevisnot/sorvor/pkg/livereload" - "github.com/pkg/errors" - "golang.org/x/net/http2" - "golang.org/x/net/http2/h2c" + "gitlab.com/tozd/go/errors" ) var ( @@ -31,28 +31,44 @@ var ( ) type Config struct { - Development bool `conf:"default:false,flag:dev"` - Root string `conf:"default:website"` + Root string `conf:"default:public"` Redirect bool `conf:"default:true"` ListenAddress string `conf:"default:localhost"` - Port int `conf:"default:3000,short:p"` - TLSPort int `conf:"default:443"` + Port int `conf:"default:8080,short:p"` + TLSPort int `conf:"default:8443"` TLS bool `conf:"default:false"` + + Development bool `conf:"default:false,flag:dev"` + ACMECA string `conf:"env:ACME_CA"` + ACMECACert string `conf:"env:ACME_CA_CERT"` + Domains string } type Server struct { *http.Server runtimeConfig *Config config *cfg.Config + log *log.Logger } -func applyDevModeOverrides(config *cfg.Config, listenAddress string) { +func applyDevModeOverrides(config *cfg.Config, runtimeConfig *Config) { config.CSP.ScriptSrc = slices.Insert(config.CSP.ScriptSrc, 0, "'unsafe-inline'") config.CSP.ConnectSrc = slices.Insert(config.CSP.ConnectSrc, 0, "'self'") + if runtimeConfig.Domains != "" { + config.Domains = strings.Split(runtimeConfig.Domains, ",") + } else { + config.Domains = []string{runtimeConfig.ListenAddress} + } + scheme := "http" + port := runtimeConfig.Port + if runtimeConfig.TLS { + scheme = "https" + port = runtimeConfig.TLSPort + } config.BaseURL = cfg.URL{ URL: &url.URL{ - Scheme: "http", - Host: listenAddress, + Scheme: scheme, + Host: net.JoinHostPort(config.Domains[0], strconv.Itoa(port)), }, } } @@ -66,19 +82,13 @@ func updateCSPHashes(config *cfg.Config, r *builder.Result) { func serverHeaderHandler(wrappedHandler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.ProtoMajor >= 2 && r.Header.Get("Host") != "" { - // net/http does this for HTTP/1.1, but not h2c - // TODO: check with HTTP/2.0 (i.e. with TLS) - r.Host = r.Header.Get("Host") - r.Header.Del("Host") - } w.Header().Set("Server", serverHeader) wrappedHandler.ServeHTTP(w, r) }) } -func rebuild(builderConfig builder.IOConfig, config *cfg.Config) error { - r, err := builder.BuildSite(builderConfig) +func rebuild(builderConfig *builder.IOConfig, config *cfg.Config, log *log.Logger) error { + r, err := builder.BuildSite(builderConfig, config, log.Named("builder")) if err != nil { return errors.WithMessage(err, "could not build site") } @@ -87,51 +97,60 @@ func rebuild(builderConfig builder.IOConfig, config *cfg.Config) error { return nil } -func New(runtimeConfig *Config) (*Server, error) { +func New(runtimeConfig *Config, log *log.Logger) (*Server, error) { + builderConfig := &builder.IOConfig{ + Destination: runtimeConfig.Root, + Development: runtimeConfig.Development, + } + if !runtimeConfig.Development { vcsConfig := &vcs.Config{} - _, err := conf.Parse("", vcsConfig) - if err != nil { - return nil, err - } - _, err = vcs.CloneOrUpdate(vcsConfig) + _, err := conf.Parse("VCS", vcsConfig) if err != nil { return nil, err } - err = os.Chdir(vcsConfig.LocalPath) - if err != nil { - return nil, err + if vcsConfig.LocalPath != "" { + _, err = vcs.CloneOrUpdate(vcsConfig, log.Named("vcs")) + if err != nil { + return nil, err + } + err = os.Chdir(runtimeConfig.Root) + if err != nil { + return nil, err + } + + builderConfig.Source = vcsConfig.LocalPath + + publicDir := filepath.Join(runtimeConfig.Root, "public") + builderConfig.Destination = publicDir + runtimeConfig.Root = publicDir + } else { + log.Warn("in production mode without VCS configuration") } - runtimeConfig.Root = "website" } - config, err := cfg.GetConfig() + config, err := cfg.GetConfig(builderConfig.Source, log.Named("config")) if err != nil { return nil, errors.WithMessage(err, "error parsing configuration file") } if runtimeConfig.Development { - applyDevModeOverrides(config, runtimeConfig.ListenAddress) + applyDevModeOverrides(config, runtimeConfig) } - listenAddress := net.JoinHostPort(runtimeConfig.ListenAddress, strconv.Itoa(runtimeConfig.Port)) top := http.NewServeMux() - builderConfig := builder.IOConfig{ - Source: "content", - Destination: runtimeConfig.Root, - Development: runtimeConfig.Development, - } - - err = rebuild(builderConfig, config) + err = rebuild(builderConfig, config, log) if err != nil { return nil, err } + fixupMIMETypes(log) + if runtimeConfig.Development { liveReload := livereload.New() top.Handle("/_/reload", liveReload) liveReload.Start() - fw, err := NewFileWatcher() + fw, err := NewFileWatcher(log.Named("watcher")) if err != nil { return nil, errors.WithMessage(err, "could not create file watcher") } @@ -151,7 +170,7 @@ func New(runtimeConfig *Config) (*Server, error) { } go fw.Start(func(filename string) { log.Info("rebuilding site", "changed_file", filename) - err := rebuild(builderConfig, config) + err := rebuild(builderConfig, config, log) if err != nil { log.Error("error rebuilding site", "error", err) } @@ -159,7 +178,7 @@ func New(runtimeConfig *Config) (*Server, error) { } loggingMux := http.NewServeMux() - mux, err := website.NewMux(config, runtimeConfig.Root) + mux, err := website.NewMux(config, runtimeConfig.Root, log.Named("website")) if err != nil { return nil, errors.Wrap(err, "could not create website mux") } @@ -167,8 +186,9 @@ func New(runtimeConfig *Config) (*Server, error) { if runtimeConfig.Redirect { loggingMux.Handle(config.BaseURL.Hostname()+"/", mux) loggingMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - newURL := config.BaseURL.JoinPath(r.URL.String()) - http.Redirect(w, r, newURL.String(), 301) + path, _ := website.CanonicalisePath(r.URL.Path) + newURL := config.BaseURL.JoinPath(path) + http.Redirect(w, r, newURL.String(), http.StatusMovedPermanently) }) } else { loggingMux.Handle("/", mux) @@ -176,7 +196,7 @@ func New(runtimeConfig *Config) (*Server, error) { top.Handle("/", serverHeaderHandler( - wrapHandlerWithLogging(loggingMux), + wrapHandlerWithLogging(loggingMux, log), ), ) @@ -186,15 +206,13 @@ func New(runtimeConfig *Config) (*Server, error) { return &Server{ Server: &http.Server{ - Addr: listenAddress, - ReadHeaderTimeout: 1 * time.Minute, - Handler: http.MaxBytesHandler(h2c.NewHandler( - top, - &http2.Server{ - IdleTimeout: 15 * time.Minute, - }, - ), 0), + ReadHeaderTimeout: 10 * time.Second, + ReadTimeout: 1 * time.Minute, + WriteTimeout: 2 * time.Minute, + IdleTimeout: 10 * time.Minute, + Handler: top, }, + log: log, config: config, runtimeConfig: runtimeConfig, }, nil @@ -217,19 +235,19 @@ func (s *Server) Start() error { } func (s *Server) Stop() chan struct{} { - log.Debug("stop called") + s.log.Debug("stop called") idleConnsClosed := make(chan struct{}) go func() { - log.Debug("shutting down server") + s.log.Debug("shutting down server") ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() err := s.Server.Shutdown(ctx) - log.Debug("server shut down") + s.log.Debug("server shut down") if err != nil { // Error from closing listeners, or context timeout: - log.Warn("HTTP server Shutdown", "error", err) + s.log.Warn("HTTP server Shutdown", "error", err) } close(idleConnsClosed) }() diff --git a/internal/server/tcp.go b/internal/server/tcp.go index 4dc3314..1627854 100644 --- a/internal/server/tcp.go +++ b/internal/server/tcp.go @@ -1,26 +1,13 @@ package server import ( - "net" - - "website/internal/listenfd" - "website/internal/log" - - "github.com/pkg/errors" + "go.alanpearce.eu/x/listenfd" ) func (s *Server) serveTCP() error { - l, err := listenfd.GetListener(0) + l, err := listenfd.GetListener(0, s.Addr, s.log.Named("tcp.listenfd")) if err != nil { - log.Warn("could not create listener from listenfd", "error", err) - } - - log.Debug("listener from listenfd?", "passed", l != nil) - if l == nil { - l, err = net.Listen("tcp", s.Addr) - if err != nil { - return errors.Wrap(err, "could not create listener") - } + return err } return s.Serve(l) diff --git a/internal/server/tls.go b/internal/server/tls.go index 370134c..9481b6a 100644 --- a/internal/server/tls.go +++ b/internal/server/tls.go @@ -2,12 +2,18 @@ package server import ( "context" + "crypto/x509" + "net" + "net/http" + "strconv" + + "go.alanpearce.eu/x/listenfd" "github.com/ardanlabs/conf/v3" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/certmagic" certmagic_redis "github.com/pberkel/caddy-storage-redis" - "github.com/pkg/errors" + "gitlab.com/tozd/go/errors" ) type redisConfig struct { @@ -19,32 +25,134 @@ type redisConfig struct { } func (s *Server) serveTLS() (err error) { - rc := &redisConfig{} - _, err = conf.Parse("REDIS", rc) + log := s.log.Named("tls") + + // setting cfg.Logger is too late somehow + certmagic.Default.Logger = log.GetLogger().Named("certmagic") + cfg := certmagic.NewDefault() + cfg.DefaultServerName = s.config.Domains[0] + + issuer := &certmagic.DefaultACME + certmagic.DefaultACME.Agreed = true + certmagic.DefaultACME.Email = s.config.Email + certmagic.DefaultACME.Logger = certmagic.Default.Logger + + if s.runtimeConfig.Development { + ca := s.runtimeConfig.ACMECA + if ca == "" { + return errors.New("can't enable tls in development without an ACME_CA") + } + + cp, err := x509.SystemCertPool() + if err != nil { + log.Warn("could not get system certificate pool", "error", err) + cp = x509.NewCertPool() + } + + if cacert := s.runtimeConfig.ACMECACert; cacert != "" { + cp.AppendCertsFromPEM([]byte(cacert)) + } + + // caddy's ACME server (step-ca) doesn't specify an OCSP server + cfg.OCSP.DisableStapling = true + + issuer = certmagic.NewACMEIssuer(cfg, certmagic.ACMEIssuer{ + CA: s.runtimeConfig.ACMECA, + TrustedRoots: cp, + DisableTLSALPNChallenge: true, + ListenHost: s.runtimeConfig.ListenAddress, + AltHTTPPort: s.runtimeConfig.Port, + AltTLSALPNPort: s.runtimeConfig.TLSPort, + }) + cfg.Issuers[0] = issuer + } else { + rc := &redisConfig{} + _, err = conf.Parse("REDIS", rc) + if err != nil { + return errors.Wrap(err, "could not parse redis config") + } + + rs := certmagic_redis.New() + rs.Address = []string{rc.Address} + rs.Username = rc.Username + rs.Password = rc.Password + rs.EncryptionKey = rc.EncryptionKey + rs.KeyPrefix = rc.KeyPrefix + + cfg.Storage = rs + err = rs.Provision(caddy.Context{ + Context: context.Background(), + }) + if err != nil { + return errors.Wrap(err, "could not provision redis storage") + } + } + + ln, err := listenfd.GetListener( + 1, + net.JoinHostPort(s.runtimeConfig.ListenAddress, strconv.Itoa(s.runtimeConfig.Port)), + log.Named("listenfd"), + ) if err != nil { - return errors.Wrap(err, "could not parse redis config") + return errors.Wrap(err, "could not bind plain socket") } - rs := certmagic_redis.New() - rs.Address = []string{rc.Address} - rs.Username = rc.Username - rs.Password = rc.Password - rs.EncryptionKey = rc.EncryptionKey - rs.KeyPrefix = rc.KeyPrefix + go func(ln net.Listener, srv *http.Server) { + httpMux := http.NewServeMux() + httpMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + if certmagic.LooksLikeHTTPChallenge(r) && issuer.HandleHTTPChallenge(w, r) { + return + } + url := r.URL + url.Scheme = "https" + port := s.config.BaseURL.Port() + if port == "" { + url.Host = r.Host + } else { + host, _, err := net.SplitHostPort(r.Host) + if err != nil { + log.Warn("error splitting host and port", "error", err) + host = r.Host + } + url.Host = net.JoinHostPort(host, s.config.BaseURL.Port()) + } + http.Redirect(w, r, url.String(), http.StatusMovedPermanently) + }) + srv.Handler = httpMux - certmagic.Default.Storage = rs - err = rs.Provision(caddy.Context{ - Context: context.Background(), + if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Error("error in http handler", "error", err) + } + }(ln, &http.Server{ + ReadHeaderTimeout: s.ReadHeaderTimeout, + ReadTimeout: s.ReadTimeout, + WriteTimeout: s.WriteTimeout, + IdleTimeout: s.IdleTimeout, }) + + log.Debug( + "starting certmagic", + "http_port", + s.runtimeConfig.Port, + "https_port", + s.runtimeConfig.TLSPort, + ) + err = cfg.ManageSync(context.TODO(), s.config.Domains) if err != nil { - return errors.Wrap(err, "could not provision redis storage") + return errors.Wrap(err, "could not enable TLS") } + tlsConfig := cfg.TLSConfig() + tlsConfig.NextProtos = append([]string{"h2", "http/1.1"}, tlsConfig.NextProtos...) - certmagic.DefaultACME.Agreed = true - certmagic.DefaultACME.Email = s.config.Email - certmagic.Default.DefaultServerName = s.config.Domains[0] - certmagic.HTTPPort = s.runtimeConfig.Port - certmagic.HTTPSPort = s.runtimeConfig.TLSPort + sln, err := listenfd.GetListenerTLS( + 0, + net.JoinHostPort(s.runtimeConfig.ListenAddress, strconv.Itoa(s.runtimeConfig.TLSPort)), + tlsConfig, + log.Named("listenfd"), + ) + if err != nil { + return errors.Wrap(err, "could not bind tls socket") + } - return certmagic.HTTPS(s.config.Domains, s.Server.Handler) + return s.Serve(sln) } diff --git a/internal/sitemap/sitemap.go b/internal/sitemap/sitemap.go index a38e277..b166f73 100644 --- a/internal/sitemap/sitemap.go +++ b/internal/sitemap/sitemap.go @@ -3,7 +3,8 @@ package sitemap import ( "io" "time" - "website/internal/config" + + "go.alanpearce.eu/website/internal/config" "github.com/snabb/sitemap" ) @@ -13,9 +14,9 @@ type Sitemap struct { Sitemap *sitemap.Sitemap } -func New(cfg config.Config) *Sitemap { +func New(cfg *config.Config) *Sitemap { return &Sitemap{ - config: &cfg, + config: cfg, Sitemap: sitemap.New(), } } diff --git a/internal/vcs/repository.go b/internal/vcs/repository.go index 8ee08b2..e034ea4 100644 --- a/internal/vcs/repository.go +++ b/internal/vcs/repository.go @@ -2,11 +2,12 @@ package vcs import ( "os" - "website/internal/config" - "website/internal/log" + + "go.alanpearce.eu/website/internal/config" + "go.alanpearce.eu/x/log" "github.com/go-git/go-git/v5" - "github.com/pkg/errors" + "gitlab.com/tozd/go/errors" ) type Config struct { @@ -17,9 +18,10 @@ type Config struct { type Repository struct { repo *git.Repository + log *log.Logger } -func CloneOrUpdate(cfg *Config) (*Repository, error) { +func CloneOrUpdate(cfg *Config, log *log.Logger) (*Repository, error) { gr, err := git.PlainClone(cfg.LocalPath, false, &git.CloneOptions{ URL: cfg.RemoteURL.String(), Progress: os.Stdout, @@ -34,8 +36,9 @@ func CloneOrUpdate(cfg *Config) (*Repository, error) { } repo := &Repository{ repo: gr, + log: log, } - _, err := repo.Update(cfg) + _, err := repo.Update() if err != nil { return nil, err } @@ -45,18 +48,19 @@ func CloneOrUpdate(cfg *Config) (*Repository, error) { return &Repository{ repo: gr, + log: log, }, nil } -func (r *Repository) Update(cfg *Config) (bool, error) { - log.Info("updating repository") +func (r *Repository) Update() (bool, error) { + r.log.Info("updating repository") head, err := r.repo.Head() if err != nil { return false, err } - log.Info("updating from", "rev", head.Hash().String()) + r.log.Info("updating from", "rev", head.Hash().String()) wt, err := r.repo.Worktree() if err != nil { return false, err @@ -67,7 +71,7 @@ func (r *Repository) Update(cfg *Config) (bool, error) { }) if err != nil { if errors.Is(err, git.NoErrAlreadyUpToDate) { - log.Info("already up-to-date") + r.log.Info("already up-to-date") return true, nil } @@ -79,7 +83,25 @@ func (r *Repository) Update(cfg *Config) (bool, error) { if err != nil { return false, err } - log.Info("updated to", "rev", head.Hash().String()) + r.log.Info("updated to", "rev", head.Hash().String()) + + return true, r.Clean(wt) +} + +func (r *Repository) Clean(wt *git.Worktree) error { + st, err := wt.Status() + if err != nil { + return err + } + + if !st.IsClean() { + err = wt.Clean(&git.CleanOptions{ + Dir: true, + }) + if err != nil { + return err + } + } - return true, nil + return nil } diff --git a/internal/website/filemap.go b/internal/website/filemap.go index 28dcd40..64b914f 100644 --- a/internal/website/filemap.go +++ b/internal/website/filemap.go @@ -10,9 +10,9 @@ import ( "path/filepath" "strings" - "website/internal/log" + "go.alanpearce.eu/x/log" - "github.com/pkg/errors" + "gitlab.com/tozd/go/errors" ) type File struct { @@ -79,7 +79,7 @@ func registerFile(urlpath string, fp string) error { return nil } -func registerContentFiles(root string) error { +func registerContentFiles(root string, log *log.Logger) error { err := filepath.WalkDir(root, func(filePath string, f fs.DirEntry, err error) error { if err != nil { return errors.WithMessagef(err, "failed to access path %s", filePath) diff --git a/internal/website/mux.go b/internal/website/mux.go index fbd648e..6844551 100644 --- a/internal/website/mux.go +++ b/internal/website/mux.go @@ -3,19 +3,19 @@ package website import ( "encoding/json" "net/http" - "path" "strings" - "website/internal/config" - ihttp "website/internal/http" - "website/internal/log" - "website/templates" + + "go.alanpearce.eu/website/internal/config" + ihttp "go.alanpearce.eu/website/internal/http" + "go.alanpearce.eu/x/log" + "go.alanpearce.eu/website/templates" "github.com/benpate/digit" "github.com/kevinpollet/nego" - "github.com/pkg/errors" + "gitlab.com/tozd/go/errors" ) -func canonicalisePath(path string) (cPath string, differs bool) { +func CanonicalisePath(path string) (cPath string, differs bool) { cPath = path if strings.HasSuffix(path, "/index.html") { cPath, differs = strings.CutSuffix(path, "index.html") @@ -31,12 +31,14 @@ type webHandler func(http.ResponseWriter, *http.Request) *ihttp.Error type WrappedWebHandler struct { config *config.Config handler webHandler + log *log.Logger } -func wrapHandler(cfg *config.Config, webHandler webHandler) WrappedWebHandler { +func wrapHandler(cfg *config.Config, webHandler webHandler, log *log.Logger) WrappedWebHandler { return WrappedWebHandler{ config: cfg, handler: webHandler, + log: log, } } @@ -44,13 +46,13 @@ func (fn WrappedWebHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { defer func() { if fail := recover(); fail != nil { w.WriteHeader(http.StatusInternalServerError) - log.Error("runtime panic!", "error", fail) + fn.log.Error("runtime panic!", "error", fail) } }() if err := fn.handler(w, r); err != nil { if strings.Contains(r.Header.Get("Accept"), "text/html") { w.WriteHeader(err.Code) - err := templates.Error(*fn.config, r.URL.Path, err).Render(r.Context(), w) + err := templates.Error(fn.config, r.URL.Path, err).Render(r.Context(), w) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } @@ -60,19 +62,18 @@ func (fn WrappedWebHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -func NewMux(cfg *config.Config, root string) (mux *http.ServeMux, err error) { +func NewMux(cfg *config.Config, root string, log *log.Logger) (mux *http.ServeMux, err error) { mux = &http.ServeMux{} - prefix := path.Join(root, "public") - log.Debug("registering content files", "prefix", prefix) - err = registerContentFiles(prefix) + log.Debug("registering content files", "root", root) + err = registerContentFiles(root, log) if err != nil { return nil, errors.WithMessagef(err, "registering content files") } templates.Setup() mux.Handle("/", wrapHandler(cfg, func(w http.ResponseWriter, r *http.Request) *ihttp.Error { - urlPath, shouldRedirect := canonicalisePath(r.URL.Path) + urlPath, shouldRedirect := CanonicalisePath(r.URL.Path) if shouldRedirect { http.Redirect(w, r, urlPath, 302) @@ -100,7 +101,7 @@ func NewMux(cfg *config.Config, root string) (mux *http.ServeMux, err error) { http.ServeFile(w, r, files[urlPath].alternatives[enc]) return nil - })) + }, log)) var acctResource = "acct:" + cfg.Email me := digit.NewResource(acctResource). |