aboutsummaryrefslogtreecommitdiffstats
path: root/website.go
diff options
context:
space:
mode:
authorclsr <clsr@clsr.net>2016-06-16 02:19:44 +0200
committerclsr <clsr@clsr.net>2016-06-16 02:19:44 +0200
commitd1d96e35472f692ace7b08822d185f14913e0ea9 (patch)
tree83ca1bca75a0634436328a924afe7f3a9f409e45 /website.go
downloadgomf-d1d96e35472f692ace7b08822d185f14913e0ea9.tar.gz
gomf-d1d96e35472f692ace7b08822d185f14913e0ea9.zip
Initial commit
Diffstat (limited to 'website.go')
-rw-r--r--website.go95
1 files changed, 95 insertions, 0 deletions
diff --git a/website.go b/website.go
new file mode 100644
index 0000000..e601bcd
--- /dev/null
+++ b/website.go
@@ -0,0 +1,95 @@
+package main
+
+import (
+ "fmt"
+ "html/template"
+ "io/ioutil"
+ "net/http"
+ "os"
+ "path"
+ "strconv"
+ "strings"
+)
+
+var templates *template.Template
+
+func initWebsite() {
+ os.MkdirAll("pages", 0755)
+ 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" {
+ 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()
+ 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)
+ }
+}