diff --git a/_example/test3/gophercool.png b/_example/test3/gophercool.png new file mode 100644 index 0000000..5705e95 Binary files /dev/null and b/_example/test3/gophercool.png differ diff --git a/_example/test3/index.md b/_example/test3/index.md new file mode 100644 index 0000000..703628f --- /dev/null +++ b/_example/test3/index.md @@ -0,0 +1,9 @@ +--- +title = "Cool" +date = 2022-07-07 +tags = ["gopher", "cool"] +--- + +# Cool + +![gophercool](./gophercool.png) \ No newline at end of file diff --git a/router/router.go b/router/router.go index 4a3ac14..9c2901f 100644 --- a/router/router.go +++ b/router/router.go @@ -1,7 +1,9 @@ package router import ( + "fmt" "net/http" + "path/filepath" "go.jolheiser.com/blog/post" "go.jolheiser.com/blog/static" @@ -18,7 +20,10 @@ func New(blog *post.Blog) *chi.Mux { m.Use(middleware.Recoverer) m.Get("/", indexHandler(blog)) - m.Get("/{post}", fileHandler(blog)) + m.Route("/{post}", func(r chi.Router) { + r.With(slashesMiddleware).Get("/", fileHandler(blog)) + r.Get("/{asset}", assetHandler(blog)) + }) m.Route("/_", func(r chi.Router) { r.Get("/sakura.css", static.SakuraCSS) }) @@ -48,3 +53,41 @@ func fileHandler(blog *post.Blog) http.HandlerFunc { } } } + +func assetHandler(blog *post.Blog) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + postName := chi.URLParam(r, "post") + p, ok := blog.Post(postName) + if !ok { + w.WriteHeader(http.StatusNotFound) + return + } + + assetName := chi.URLParam(r, "asset") + apn := filepath.Join(filepath.Dir(p.Path), assetName) + http.ServeFile(w, r, apn) + } +} + +func slashesMiddleware(next http.Handler) http.Handler { + fn := func(w http.ResponseWriter, r *http.Request) { + var path string + rctx := chi.RouteContext(r.Context()) + if rctx != nil && rctx.RoutePath != "" { + path = rctx.RoutePath + } else { + path = r.URL.Path + } + if len(path) > 1 && path[len(path)-1] != '/' { + path += "/" + if r.URL.RawQuery != "" { + path = fmt.Sprintf("%s?%s", path, r.URL.RawQuery) + } + redirectURL := fmt.Sprintf("//%s%s", r.Host, path) + http.Redirect(w, r, redirectURL, 301) + return + } + next.ServeHTTP(w, r) + } + return http.HandlerFunc(fn) +} diff --git a/static/index.tmpl b/static/index.tmpl index f2d61f5..7e59186 100644 --- a/static/index.tmpl +++ b/static/index.tmpl @@ -22,7 +22,7 @@

Blog Posts

{{range .SortedPosts}}
- {{.Title}}
+ {{.Title}}
{{if .Author}}@{{.Author}}{{end}}{{.Date.Format "Jan 2, 2006"}}
{{range .Tags}}{{.}} {{end}}
diff --git a/static/post.tmpl b/static/post.tmpl index 66b1ce1..4f1ebef 100644 --- a/static/post.tmpl +++ b/static/post.tmpl @@ -4,10 +4,10 @@ {{.Title}} - + - Index + Index {{.Content}}