Add assets handler to gemini

This commit is contained in:
Brian Picciano 2023-01-21 19:11:41 +01:00
parent bde3751fab
commit 2ca44b60d4
2 changed files with 35 additions and 2 deletions

View File

@ -5,8 +5,10 @@ import (
"context"
"errors"
"fmt"
"mime"
"net/url"
"os"
"path"
"strings"
"git.sr.ht/~adnano/go-gemini"
@ -142,7 +144,7 @@ func postsMiddleware(tplHandler gemini.Handler) gemini.Handler {
r *gemini.Request,
) {
id := strings.TrimPrefix(r.URL.Path, "/posts/")
id := path.Base(r.URL.Path)
id = strings.TrimSuffix(id, ".gmi")
if id == "index" {
@ -160,6 +162,37 @@ func postsMiddleware(tplHandler gemini.Handler) gemini.Handler {
})
}
func (a *api) assetsMiddleware() gemini.Handler {
return gemini.HandlerFunc(func(
ctx context.Context,
rw gemini.ResponseWriter,
r *gemini.Request,
) {
id := path.Base(r.URL.Path)
mimeType := mime.TypeByExtension(path.Ext(id))
ctx = mctx.Annotate(ctx, "assetID", id, "mimeType", mimeType)
if mimeType != "" {
rw.SetMediaType(mimeType)
}
err := a.params.PostAssetStore.Get(id, rw)
if errors.Is(err, post.ErrAssetNotFound) {
rw.WriteHeader(gemini.StatusNotFound, "Asset not found, sorry!")
return
} else if err != nil {
a.params.Logger.Error(ctx, "error fetching asset", err)
rw.WriteHeader(gemini.StatusTemporaryFailure, err.Error())
return
}
})
}
func (a *api) handler() (gemini.Handler, error) {
tplHandler, err := a.tplHandler()
@ -169,6 +202,7 @@ func (a *api) handler() (gemini.Handler, error) {
mux := new(gemini.Mux)
mux.Handle("/posts/", postsMiddleware(tplHandler))
mux.Handle("/assets/", a.assetsMiddleware())
mux.Handle("/", tplHandler)
var h gemini.Handler

View File

@ -200,7 +200,6 @@ func (a *api) tplHandler() (gemini.Handler, error) {
tpl := allTpls.Lookup(tplPath)
if tpl == nil {
a.params.Logger.WarnString(ctx, "page not found")
rw.WriteHeader(gemini.StatusNotFound, "Page not found, sorry!")
return
}