routes/template.go (view raw)
1package routes
2
3import (
4 "bytes"
5 "html/template"
6 "io"
7 "log"
8 "net/http"
9 "path/filepath"
10 "strings"
11
12 "icyphox.sh/legit/git"
13)
14
15func (d *deps) Write404(w http.ResponseWriter) {
16 tpath := filepath.Join(d.c.Dirs.Templates, "*")
17 t := template.Must(template.ParseGlob(tpath))
18 w.WriteHeader(404)
19 if err := t.ExecuteTemplate(w, "404", nil); err != nil {
20 log.Printf("404 template: %s", err)
21 }
22}
23
24func (d *deps) Write500(w http.ResponseWriter) {
25 tpath := filepath.Join(d.c.Dirs.Templates, "*")
26 t := template.Must(template.ParseGlob(tpath))
27 w.WriteHeader(500)
28 if err := t.ExecuteTemplate(w, "500", nil); err != nil {
29 log.Printf("500 template: %s", err)
30 }
31}
32
33func (d *deps) listFiles(files []git.NiceTree, data map[string]any, w http.ResponseWriter) {
34 tpath := filepath.Join(d.c.Dirs.Templates, "*")
35 t := template.Must(template.ParseGlob(tpath))
36
37 data["files"] = files
38 data["meta"] = d.c.Meta
39
40 if err := t.ExecuteTemplate(w, "repo", data); err != nil {
41 log.Println(err)
42 return
43 }
44}
45
46func countLines(r io.Reader) (int, error) {
47 buf := make([]byte, 32*1024)
48 count := 0
49 nl := []byte{'\n'}
50
51 for {
52 c, err := r.Read(buf)
53 count += bytes.Count(buf[:c], nl)
54
55 switch {
56 case err == io.EOF:
57 return count, nil
58 case err != nil:
59 return 0, err
60 }
61 }
62}
63
64func (d *deps) showFile(content string, data map[string]any, w http.ResponseWriter) {
65 tpath := filepath.Join(d.c.Dirs.Templates, "*")
66 t := template.Must(template.ParseGlob(tpath))
67
68 lc, err := countLines(strings.NewReader(content))
69 if err != nil {
70 // Non-fatal, we'll just skip showing line numbers in the template.
71 log.Printf("counting lines: %s", err)
72 }
73
74 lines := make([]int, lc)
75 if lc > 0 {
76 for i := range lines {
77 lines[i] = i + 1
78 }
79 }
80
81 data["linecount"] = lines
82 data["content"] = content
83 data["meta"] = d.c.Meta
84
85 if err := t.ExecuteTemplate(w, "file", data); err != nil {
86 log.Println(err)
87 return
88 }
89}