summaryrefslogtreecommitdiffhomepage
path: root/derelict.go
blob: 1c9339938cce1882235bc573a7d0b44cc4053602 (plain)
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
package main

import (
	"embed"
	"encoding/json"
	"html/template"
	"log"
	"net/http"
	"os"

	"github.com/gorilla/mux"
)

//go:embed *.css *.js *.svg
var content embed.FS

//go:embed *.tmpl
var internal embed.FS

var (
	storage   Storage
	templates *template.Template
)

func main() {
	storage.Path = os.Getenv("DERELICTROOT")
	if storage.Path == "" {
		storage.Path = ".derelict"
	}

	port := os.Getenv("DERELICTPORT")
	if port == "" {
		port = "8080"
	}

	storage.MustInit()

	templates = template.Must(template.ParseFS(internal, "*.tmpl"))

	router := mux.NewRouter()
	router.HandleFunc("/", handleRecent).Methods("GET")
	router.HandleFunc("/view/{id:[_0-9a-f]+}", handleView).Methods("GET")
	router.HandleFunc("/battles", handleBattlesPost).Methods("POST")
	router.HandleFunc("/battles/{id:[_0-9a-f]+}", handleBattlesId).Methods("GET")
	router.PathPrefix("/").Handler(http.FileServer(http.FS(content)))
	log.Fatal(http.ListenAndServe(":"+port, router))
}

func handleBattlesPost(w http.ResponseWriter, r *http.Request) {
	authorized, err := storage.CanPost(r.Header.Get("Derelict-Token"))
	if err != nil {
		http.Error(w, "Invalid token", http.StatusBadRequest)
		return
	}
	if !authorized {
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}
	decoder := json.NewDecoder(r.Body)
	var battle Battle
	if err := decoder.Decode(&battle); err != nil {
		http.Error(w, "Error reading battle", http.StatusBadRequest)
		return
	}
	err = storage.AddBattle(&battle)
	if err != nil {
		http.Error(w, "Error writing battle", http.StatusInternalServerError)
		return
	}
	w.Write([]byte(battle.Id))
}

func handleBattlesId(w http.ResponseWriter, r *http.Request) {
	storage.ServeBattle(mux.Vars(r)["id"], w, r)
}

func handleRecent(w http.ResponseWriter, r *http.Request) {
	battles, err := storage.ListRecentBattles(10)
	if err != nil {
		http.Error(w, "Error getting recent battles", http.StatusInternalServerError)
		return
	}
	templates.ExecuteTemplate(w, "recent", battles)
}

func handleView(w http.ResponseWriter, r *http.Request) {
	id := mux.Vars(r)["id"]
	templates.ExecuteTemplate(w, "view", id)
}