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
|
package main
import (
"fmt"
"html/template"
"io/ioutil"
"math/rand"
"net/http"
"os"
"path"
"strconv"
"strings"
)
var templates *template.Template
func initWebsite() {
pages, err := ioutil.ReadDir("pages")
if err != nil {
panic(err)
}
templates = template.Must(template.ParseGlob("pages/*.html"))
for _, page := range pages {
if path.Ext(page.Name()) == ".html" && page.Name()[0] != '_' {
http.HandleFunc("/"+page.Name(), handlePage)
if page.Name() == "index.html" {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
handlePage(w, r)
})
}
}
}
http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir("static"))))
http.HandleFunc("/favicon.ico", handleFavicon)
}
func humanize(bytes int64) string {
units := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"}
i := 0
n := float64(bytes)
for n >= 1024 && i < len(units)-1 {
n /= 1024
i += 1
}
return strconv.FormatFloat(n, 'f', -1, 64) + " " + units[i]
}
func handleFavicon(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/favicon.ico")
}
type pageContext struct {
SiteName string
Abuse string
Contact string
MaxSizeBytes int64
MaxSize string
Pages map[string]string
Result response
}
func newContext() pageContext {
pages := make(map[string]string)
for _, t := range templates.Templates() {
n := t.Name()
if n[0] != '_' {
title := n[:len(n)-len(path.Ext(n))]
title = strings.ToUpper(title[0:1]) + title[1:]
pages[title] = n
}
}
return pageContext{
SiteName: siteName,
Abuse: abuseMail,
Contact: contactMail,
MaxSizeBytes: storage.MaxSize,
MaxSize: humanize(storage.MaxSize),
Pages: pages,
}
}
func handlePage(w http.ResponseWriter, r *http.Request) {
page := strings.TrimLeft(r.URL.Path, "/")
if page == "" {
page = "index.html"
}
if err := templates.ExecuteTemplate(w, page, newContext()); err != nil {
fmt.Fprintln(os.Stderr, err)
}
}
func handleGrill(w http.ResponseWriter, r *http.Request) {
grills, err := ioutil.ReadDir("static/grill/")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/static/grill/"+grills[rand.Intn(len(grills))].Name(), http.StatusFound)
}
|