-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
88 lines (70 loc) · 1.75 KB
/
main.go
File metadata and controls
88 lines (70 loc) · 1.75 KB
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
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"roggl-server/trie"
"strings"
"github.com/julienschmidt/httprouter"
)
var t *trie.Trie
const (
prefix = "/api"
port = "8080"
)
func list(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
encoder.Encode(t)
}
func create(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
path := strings.Split(ps[0].Value, "+")
if err := t.Add(path); err != nil {
w.WriteHeader(http.StatusInternalServerError) //REVIEW
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusCreated)
saveTrie()
}
func start(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
path := strings.Split(ps[0].Value, "+")
if t.IsRecording() {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("already recording"))
return
}
if ok := t.Record(path); !ok {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("project doesn't exist"))
return
}
w.WriteHeader(http.StatusCreated)
saveTrie()
}
func stop(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
if ok := t.Stop(); !ok {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("not recording"))
return
}
w.WriteHeader(http.StatusOK)
saveTrie()
}
func main() {
if len(os.Args) > 1 {
fname = os.Args[1]
log.Printf("loading and saving trie from/to %s\n", fname)
} else {
log.Println("no trie filename given, not loading or saving anything")
}
loadTrie()
router := httprouter.New()
router.GET(prefix, list)
router.POST(prefix+"/projects/:path", create)
router.POST(prefix+"/projects/:path/start", start)
router.POST(prefix+"/stop", stop)
log.Print("listening on " + port)
log.Fatal(http.ListenAndServe(":"+port, router))
}