legit/routes/template.go

86 lines
1.6 KiB
Go
Raw Normal View History

2022-12-11 05:52:47 +00:00
package routes
import (
2022-12-13 06:20:39 +00:00
"bytes"
"io"
2022-12-11 08:48:39 +00:00
"log"
2022-12-11 05:52:47 +00:00
"net/http"
2022-12-13 06:20:39 +00:00
"strings"
2022-12-11 05:52:47 +00:00
2022-12-19 03:32:23 +00:00
"git.icyphox.sh/legit/git"
2022-12-11 05:52:47 +00:00
)
2022-12-12 15:23:58 +00:00
func (d *deps) Write404(w http.ResponseWriter) {
2022-12-11 05:52:47 +00:00
w.WriteHeader(404)
if err := d.t.ExecuteTemplate(w, "404", nil); err != nil {
2022-12-12 15:23:58 +00:00
log.Printf("404 template: %s", err)
}
2022-12-11 05:52:47 +00:00
}
2022-12-12 15:23:58 +00:00
func (d *deps) Write500(w http.ResponseWriter) {
2022-12-11 05:52:47 +00:00
w.WriteHeader(500)
if err := d.t.ExecuteTemplate(w, "500", nil); err != nil {
2022-12-12 15:23:58 +00:00
log.Printf("500 template: %s", err)
}
2022-12-11 05:52:47 +00:00
}
2022-12-11 15:47:04 +00:00
func (d *deps) listFiles(files []git.NiceTree, data map[string]any, w http.ResponseWriter) {
2022-12-11 08:48:39 +00:00
data["files"] = files
data["meta"] = d.c.Meta
if err := d.t.ExecuteTemplate(w, "tree", data); err != nil {
2022-12-11 08:48:39 +00:00
log.Println(err)
return
}
}
2022-12-13 06:20:39 +00:00
func countLines(r io.Reader) (int, error) {
buf := make([]byte, 32*1024)
bufLen := 0
2022-12-13 06:20:39 +00:00
count := 0
nl := []byte{'\n'}
for {
c, err := r.Read(buf)
if c > 0 {
bufLen += c
}
2022-12-13 06:20:39 +00:00
count += bytes.Count(buf[:c], nl)
switch {
case err == io.EOF:
/* handle last line not having a newline at the end */
if bufLen >= 1 && buf[(bufLen-1)%(32*1024)] != '\n' {
count++
}
2022-12-13 06:20:39 +00:00
return count, nil
case err != nil:
return 0, err
}
}
}
2022-12-11 15:47:04 +00:00
func (d *deps) showFile(content string, data map[string]any, w http.ResponseWriter) {
2022-12-13 06:20:39 +00:00
lc, err := countLines(strings.NewReader(content))
if err != nil {
// Non-fatal, we'll just skip showing line numbers in the template.
log.Printf("counting lines: %s", err)
}
lines := make([]int, lc)
if lc > 0 {
for i := range lines {
lines[i] = i + 1
}
}
2022-12-11 15:47:04 +00:00
2022-12-13 06:20:39 +00:00
data["linecount"] = lines
2022-12-11 08:48:39 +00:00
data["content"] = content
data["meta"] = d.c.Meta
if err := d.t.ExecuteTemplate(w, "file", data); err != nil {
2022-12-11 08:48:39 +00:00
log.Println(err)
return
2022-12-11 05:52:47 +00:00
}
}