From 10c60b3c9ba2c17419534cf4089328a66568e4f1 Mon Sep 17 00:00:00 2001 From: Mitchell Riedstra Date: Sat, 3 Dec 2022 13:38:05 -0500 Subject: Add a couple handlers to serve up JSON and markdown --- page/renderMarkdown.go | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 page/renderMarkdown.go (limited to 'page/renderMarkdown.go') diff --git a/page/renderMarkdown.go b/page/renderMarkdown.go new file mode 100644 index 0000000..c876169 --- /dev/null +++ b/page/renderMarkdown.go @@ -0,0 +1,69 @@ +package page + +import ( + "bytes" + "errors" + "io/fs" + "net/http" + "path/filepath" +) + +// RenderMarkdown is analogous to Render, except it spits out rendered markdown +// as text/plain +func RenderMarkdown(w http.ResponseWriter, r *http.Request, + path string, vars map[string]interface{}, statusCode int) { + u := getURLPath(r) + + u = filepath.Join(".", u) + + // Sepcifically use the specified path for the page + p := NewPage(path) + + if vars != nil { + p.Vars = vars + } + + buf := &bytes.Buffer{} + + err := p.Render(buf) + if err != nil { + if errors.Is(err, fs.ErrNotExist) { + w.WriteHeader(http.StatusNotFound) + w.Header().Set("Content-type", "text/plain") + w.Write([]byte("Not found")) + + return + } + + Logger.Printf("%s %s path: %s rendering encountered: %s", + r.RemoteAddr, + r.Method, + u, + err) + w.WriteHeader(http.StatusInternalServerError) + w.Header().Set("Content-type", "text/plain") + w.Write([]byte("Internal server error")) + + return + } + + // Error was handled above + md, _ := p.GetMarkdown() + + w.WriteHeader(statusCode) + w.Header().Set("Content-type", "text/plain") + + _, err = w.Write([]byte(md)) + if err != nil { + Logger.Printf("%s %s %d %s: while writing buf: %s", + r.RemoteAddr, + r.Method, + statusCode, + u, + err) + + return + } + + Logger.Printf("%s %s %d %s", r.RemoteAddr, r.Method, statusCode, u) +} -- cgit v1.2.3