-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
95 lines (78 loc) · 2.32 KB
/
main.go
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
package main
import (
"cloud.google.com/go/datastore"
"context"
"github.com/minisu/ipdip/repository/inmemory"
"github.com/satori/go.uuid"
"html/template"
"log"
"net/http"
"os"
"strings"
)
func main() {
ctx := context.Background()
dsClient, err := datastore.NewClient(ctx, "ipdip-334118")
decisionTmpl := template.Must(template.ParseFiles("templates/decision.gohtml"))
if err != nil {
log.Fatalln(err)
return
}
defer dsClient.Close()
//repository := firestore.NewFirestoreDecisionRepo(dsClient, ctx)
repository := inmemory.NewInMemoryDecisionRepo()
decisionMaker := NewDecisionMaker(repository)
http.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
http.HandleFunc("GET /decision/{id}", func(w http.ResponseWriter, r *http.Request) {
decisionId, err := uuid.FromString(r.PathValue("id"))
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
d, err := decisionMaker.getDecision(decisionId)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
decisionTmpl.Execute(w, d)
})
http.HandleFunc("POST /decision/{id}/decide", func(w http.ResponseWriter, r *http.Request) {
decisionId, err := uuid.FromString(r.PathValue("id"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
_, err = decisionMaker.decide(decisionId)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
http.Redirect(w, r, "/decision/"+decisionId.String(), http.StatusFound)
})
http.HandleFunc("POST /decision", func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
name := r.PostForm["name"][0]
options := strings.Split(r.PostForm["options"][0], "\n")
id, err := decisionMaker.createDecision(name, options)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/decision/"+id.String(), http.StatusFound)
})
// Determine port for HTTP service.
port := os.Getenv("PORT")
if port == "" {
port = "8080"
log.Printf("defaulting to port %s", port)
}
log.Printf("Listening on :%s...", port)
if err := http.ListenAndServe(":"+port, http.DefaultServeMux); err != nil {
log.Fatal(err)
}
}