-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler.go
90 lines (77 loc) · 2.05 KB
/
handler.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
package makaroni
import (
"fmt"
"github.com/google/uuid"
"log"
"net/http"
"strings"
)
var contentTypeHTML = "text/html"
var contentTypeText = "text/plain"
type PasteHandler struct {
IndexHTML []byte
OutputHTMLPre []byte
Upload func(key string, content string, contentType string) error
Style string
ResultURLPrefix string
MultipartMaxMemory int64
}
func RespondServerInternalError(w http.ResponseWriter, err error) {
w.WriteHeader(http.StatusInternalServerError)
log.Println(err)
}
func (p *PasteHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodGet {
w.Header().Set("Content-Type", contentTypeHTML)
w.WriteHeader(http.StatusOK)
if _, err := w.Write(p.IndexHTML); err != nil {
log.Println(err)
}
return
}
if req.Method != http.MethodPost {
w.WriteHeader(http.StatusBadRequest)
return
}
if err := req.ParseMultipartForm(p.MultipartMaxMemory); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
content := req.Form.Get("content")
if len(content) == 0 {
w.WriteHeader(http.StatusBadRequest)
return
}
syntax := req.Form.Get("syntax")
if len(syntax) == 0 {
syntax = "plaintext"
}
uuidV4, err := uuid.NewRandom()
if err != nil {
RespondServerInternalError(w, err)
return
}
keyRaw := uuidV4.String()
keyHTML := keyRaw + ".html"
urlHTML := p.ResultURLPrefix + keyHTML
urlRaw := p.ResultURLPrefix + keyRaw
builder := strings.Builder{}
// todo: better templating
builder.Write(p.OutputHTMLPre)
builder.Write([]byte(fmt.Sprintf("<div class=\"nav\"><a href=\"%s\">raw</a></div>", urlRaw)))
if err := highlight(&builder, content, syntax, p.Style); err != nil {
RespondServerInternalError(w, err)
return
}
html := builder.String()
if err := p.Upload(keyRaw, content, contentTypeText); err != nil {
RespondServerInternalError(w, err)
return
}
if err := p.Upload(keyHTML, html, contentTypeHTML); err != nil {
RespondServerInternalError(w, err)
return
}
w.Header().Set("Location", urlHTML)
w.WriteHeader(http.StatusFound)
}