render markdown files in file viewer
1 file changed, 29 insertions(+), 8 deletions(-)
changed files
M routes/template.go → routes/template.go
@@ -2,13 +2,17 @@ package routes import ( "bytes" + "fmt" "io" "log" "net/http" + "path/filepath" "strings" "alin.ovh/elgit/git" "alin.ovh/elgit/templates" + "github.com/microcosm-cc/bluemonday" + "github.com/russross/blackfriday/v2" ) func (d *deps) Write404(w http.ResponseWriter) {@@ -90,6 +94,22 @@ } } func (d *deps) showFile(content string, data map[string]any, w http.ResponseWriter) { + var renderedContent string + if len(content) > 0 { + switch filepath.Ext(data["path"].(string)) { + case ".md": + unsafe := blackfriday.Run( + []byte(content), + blackfriday.WithExtensions(blackfriday.CommonExtensions), + ) + html := bluemonday.UGCPolicy().SanitizeBytes(unsafe) + renderedContent = string(html) + default: + safe := bluemonday.UGCPolicy().SanitizeBytes([]byte(content)) + renderedContent = fmt.Sprintf(`<pre>%s</pre>`, safe) + } + } + lc, err := countLines(strings.NewReader(content)) if err != nil { // Non-fatal, we'll just skip showing line numbers in the template.@@ -104,14 +124,15 @@ } } pageData := templates.PageData{ - Meta: d.c.Meta, - DisplayName: getDisplayName(data["name"].(string)), - LineCount: lines, - Content: content, - Name: data["name"].(string), - Ref: data["ref"].(string), - Description: data["desc"].(string), - Path: data["path"].(string), + Meta: d.c.Meta, + DisplayName: getDisplayName(data["name"].(string)), + LineCount: lines, + Content: content, + RenderedContent: renderedContent, + Name: data["name"].(string), + Ref: data["ref"].(string), + Description: data["desc"].(string), + Path: data["path"].(string), } if err := templates.FilePage(pageData).Render(w); err != nil {