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
|
package main
import (
"embed"
"github.com/gorilla/mux"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"sort"
)
//go:embed *.json *.css *.js *.svg
var content embed.FS
//go:embed *.tmpl
var internal embed.FS
var templates *template.Template
var root string
func main() {
initRoot()
port := os.Getenv("DERELICTPORT")
if port == "" {
port = "8080"
}
templates = template.Must(template.ParseFS(internal, "*.tmpl"))
router := mux.NewRouter()
router.HandleFunc("/", handleRecent).Methods("GET")
router.HandleFunc("/view/{id:[_0-9]+}", handleView).Methods("GET")
router.HandleFunc("/battles/", handleBattlesPost).Methods("POST")
router.HandleFunc("/battles/{id:[_0-9]+}", handleBattlesId).Methods("GET")
router.PathPrefix("/").Handler(http.FileServer(http.FS(content)))
log.Fatal(http.ListenAndServe(":"+port, router))
}
func initRoot() {
root = os.Getenv("DERELICTROOT")
if root == "" {
root = ".derelict"
}
os.Mkdir(root, 0755)
os.Mkdir(root+"/battles", 0755)
}
func handleBattlesPost(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotImplemented)
}
func handleBattlesId(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
w.Header().Add("Content-Type", "application/json")
http.ServeFile(w, r, root+"/battles/"+id)
}
func handleRecent(w http.ResponseWriter, r *http.Request) {
files, err := ioutil.ReadDir(root + "/battles")
if err != nil {
panic(err)
}
sort.Slice(files, func(lhs, rhs int) bool {
return files[lhs].ModTime().After(files[rhs].ModTime())
})
count := 10
if count > len(files) {
count = len(files)
}
templates.ExecuteTemplate(w, "recent", files[:count])
}
func handleView(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
templates.ExecuteTemplate(w, "view", id)
}
|