From 2ca44b60d4cdbd6158604b5c25f80a9139f8c716 Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Sat, 21 Jan 2023 19:11:41 +0100 Subject: [PATCH] Add assets handler to gemini --- src/gmi/gmi.go | 36 +++++++++++++++++++++++++++++++++++- src/gmi/tpl.go | 1 - 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/gmi/gmi.go b/src/gmi/gmi.go index b543e05..9ef6e19 100644 --- a/src/gmi/gmi.go +++ b/src/gmi/gmi.go @@ -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 diff --git a/src/gmi/tpl.go b/src/gmi/tpl.go index 9e0bc64..3022fe2 100644 --- a/src/gmi/tpl.go +++ b/src/gmi/tpl.go @@ -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 }