-
Notifications
You must be signed in to change notification settings - Fork 0
/
html.go
112 lines (105 loc) · 2.44 KB
/
html.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package pimbin
import (
"fmt"
"html/template"
"io/ioutil"
"net/http"
"strings"
stdhtml "html"
"github.com/alecthomas/chroma"
"github.com/alecthomas/chroma/formatters/html"
"github.com/alecthomas/chroma/lexers"
"github.com/alecthomas/chroma/styles"
)
type pasteView struct {
SiteName string
BaseURL string
Paste Paste
}
const pasteTemplate = `{{ define "paste" }}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="{{ .BaseURL }}style.css">
<title>{{ .SiteName }}</title>
<meta name="description" content = "
{{ range .Paste.Files -}}
- {{ .Name }}
{{ end -}}">
</head>
<body>
{{ if lt 1 (len .Paste.Files)}}
<h1>files</h1>
<ul id="file-index">
{{ range .Paste.Files }}
<li>
<a href="#{{.Name}}">{{.Name}}</a>
</li>
{{ end }}
</ul>
{{ end }}
{{ range .Paste.Files}}
{{ if lt 1 (len $.Paste.Files)}}
{{ end }}
<h1 id="{{.Name}}" class="filename">{{.Name}}</h1>
<a href="{{ $.BaseURL }}raw/{{ .Hash }}/{{ .Name }}">raw</a>
{{ renderFile . }}
{{ end }}
</body>
</html>
{{end}}`
func (s *Server) renderPaste(w http.ResponseWriter, p *Paste) {
funcMap := template.FuncMap{"renderFile": s.renderFile}
t, err := template.New("paste").Funcs(funcMap).Parse(pasteTemplate)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
err = t.ExecuteTemplate(w, "paste", pasteView{
BaseURL: s.Config.BaseURL,
SiteName: s.Config.SiteName,
Paste: *p})
if err != nil {
http.Error(w, err.Error(), 500)
return
}
}
func (s *Server) renderFile(f File) template.HTML {
lexer := lexers.Match(f.Name)
if lexer == nil {
lexer = lexers.Fallback
}
lexer = chroma.Coalesce(lexer)
style := styles.Get("dracula")
if style == nil {
style = styles.Fallback
}
formatter := html.New(
html.WithClasses(true),
html.LineNumbersInTable(true),
html.LinkableLineNumbers(true, stdhtml.EscapeString(f.Name+"-L")),
html.WithLineNumbers(true))
r, ctype, err := s.getPasteFile(f)
defer r.Close()
switch {
case strings.HasPrefix(ctype, "text/"):
break
case strings.HasPrefix(ctype, "image/"):
return template.HTML(fmt.Sprintf(`<img src="%sraw/%s" alt="%s">`,
s.Config.BaseURL, f.Hash, f.Name))
default:
return template.HTML("<p>(binary file not rendered)</p>")
}
contents, err := ioutil.ReadAll(r)
if err != nil {
return ""
}
iterator, err := lexer.Tokenise(nil, string(contents))
var b strings.Builder
err = formatter.Format(&b, style, iterator)
if err != nil {
return ""
}
return template.HTML(b.String())
}