Sergiusz Bazanski | c881cf3 | 2020-04-08 20:03:12 +0200 | [diff] [blame^] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "html/template" |
| 6 | "net/http" |
| 7 | "strings" |
| 8 | |
| 9 | "code.hackerspace.pl/hscloud/devtools/hackdoc/config" |
| 10 | "code.hackerspace.pl/hscloud/devtools/hackdoc/source" |
| 11 | |
| 12 | "github.com/golang/glog" |
| 13 | "gopkg.in/russross/blackfriday.v2" |
| 14 | ) |
| 15 | |
| 16 | func (s *service) handleMarkdown(w http.ResponseWriter, r *http.Request, src source.Source, branch, path string, cfg *config.Config) { |
| 17 | data, err := src.ReadFile(path) |
| 18 | if err != nil { |
| 19 | glog.Errorf("ReadFile(%q): %w", err) |
| 20 | handle500(w, r) |
| 21 | return |
| 22 | } |
| 23 | |
| 24 | rendered := blackfriday.Run([]byte(data)) |
| 25 | |
| 26 | logRequest(w, r, "serving markdown at %s, cfg %+v", path, cfg) |
| 27 | |
| 28 | // TODO(q3k): allow markdown files to override which template to load |
| 29 | tmpl, ok := cfg.Templates["default"] |
| 30 | if !ok { |
| 31 | glog.Errorf("No default template found for %s", path) |
| 32 | // TODO(q3k): implement fallback template |
| 33 | w.Write(rendered) |
| 34 | return |
| 35 | } |
| 36 | |
| 37 | vars := map[string]interface{}{ |
| 38 | "Rendered": template.HTML(rendered), |
| 39 | "Title": path, |
| 40 | "Path": path, |
| 41 | "PathInDepot": strings.TrimPrefix(path, "//"), |
| 42 | "HackdocURL": flagHackdocURL, |
| 43 | "GitwebURL": fmt.Sprintf(flagGitwebURLPattern, flagGitwebDefaultBranch, strings.TrimPrefix(path, "//")), |
| 44 | } |
| 45 | err = tmpl.Execute(w, vars) |
| 46 | if err != nil { |
| 47 | glog.Errorf("Could not execute template for %s: %v", err) |
| 48 | } |
| 49 | } |