-
Notifications
You must be signed in to change notification settings - Fork 22
/
server.go
107 lines (91 loc) · 2.48 KB
/
server.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
package pokepaste
import (
"encoding/json"
"log"
"net/http"
"path/filepath"
"regexp"
"runtime"
)
var Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Strict-Transport-Security", "max-age=31536000")
w.Header().Set("Content-Security-Policy", "default-src 'none'; font-src 'self'; img-src 'self'; script-src 'self'; style-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'")
if m := path.FindStringSubmatch(r.URL.Path); m != nil {
id, err := decodeID(m[1])
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
servePaste(w, id, m[2])
} else if m := pathOld.FindStringSubmatch(r.URL.Path); m != nil {
id, err := decodeOldID(m[1])
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if id >= 1000 {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
servePaste(w, id, m[2])
} else if r.URL.Path == "/create" {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
paste := r.Form.Get("paste")
if len(paste) == 0 {
http.Error(w, "No (or Invalid) Paste", http.StatusBadRequest)
return
}
title := r.Form.Get("title")
author := r.Form.Get("author")
notes := r.Form.Get("notes")
id, err := postPaste(&paste, &title, &author, ¬es)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/"+encodeID(id), http.StatusSeeOther)
} else {
assets.ServeHTTP(w, r)
}
})
var (
dir = getDir()
assets = http.FileServer(http.Dir(filepath.Join(dir, "assets")))
path = regexp.MustCompile(`^/([0-9a-f]{16})(/.*)?$`)
pathOld = regexp.MustCompile(`^/([0-9]{1,10})(/.*)?$`)
)
func getDir() string {
_, file, _, ok := runtime.Caller(1)
if !ok {
log.Fatal("Could not recover file path")
}
return filepath.Dir(file)
}
func servePaste(w http.ResponseWriter, id uint64, p string) {
paste, title, author, notes, err := getPaste(id)
if err != nil {
http.NotFound(w, nil)
return
}
switch p {
case "", "/":
renderPaste(w, paste, title, author, notes)
case "/raw":
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Write(paste)
case "/json":
w.Header().Set("Access-Control-Allow-Origin", "*")
json.NewEncoder(w).Encode(map[string]interface{}{
"paste": string(paste),
"title": string(title),
"author": string(author),
"notes": string(notes),
})
default:
http.NotFound(w, nil)
}
}