-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
187 lines (159 loc) · 5.2 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package main
import (
"bytes"
"cloud.google.com/go/storage"
"context"
"crypto/md5"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
var client *storage.Client
const bucket = "aorta-routes.appspot.com"
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
var err error
// This magically pulls credentials from AppEngine
client, err = storage.NewClient(context.Background())
if err != nil {
log.Fatalf("Can't set up GCS client: %v", err)
}
// Versioning is useful in case we get fancier later, like actually having accounts
http.HandleFunc("/v1/get", get)
http.HandleFunc("/v1/create", create)
http.HandleFunc("/v1/get-ltn", getLTN)
http.HandleFunc("/v1/create-ltn", createLTN)
// TODO List
log.Printf("Serving on port %v", port)
http.ListenAndServe(":"+port, nil)
}
func get(resp http.ResponseWriter, req *http.Request) {
// TODO Actually be careful with CORS
resp.Header().Set("Access-Control-Allow-Origin", "*")
values, ok := req.URL.Query()["id"]
if !ok || len(values[0]) < 1 {
http.Error(resp, "missing ID param", http.StatusBadRequest)
return
}
id := values[0]
// TODO Do we need to sanitize the input?
obj := client.Bucket(bucket).Object(fmt.Sprintf("proposals/%v", id))
r, err := obj.NewReader(context.Background())
if err != nil {
http.Error(resp, fmt.Sprintf("new reader failed: %v", err), http.StatusInternalServerError)
return
}
defer r.Close()
if _, err := io.Copy(resp, r); err != nil {
http.Error(resp, fmt.Sprintf("reading failed: %v", err), http.StatusInternalServerError)
return
}
}
func create(resp http.ResponseWriter, req *http.Request) {
resp.Header().Set("Access-Control-Allow-Origin", "*")
rawJSON, mapName, err := validateJSON(req.Body)
if err != nil {
log.Printf("Invalid JSON in create call: %v", err)
http.Error(resp, err.Error(), http.StatusBadRequest)
return
}
checksum := fmt.Sprintf("%x", md5.Sum(rawJSON))
// If the proposal already exists, overwriting it with the same thing will be idempotent.
obj := client.Bucket(bucket).Object(fmt.Sprintf("proposals/%v", checksum))
w := obj.NewWriter(context.Background())
if _, err := w.Write(rawJSON); err != nil {
http.Error(resp, fmt.Sprintf("writing failed: %v", err), http.StatusInternalServerError)
return
}
if err := w.Close(); err != nil {
http.Error(resp, fmt.Sprintf("closing after write failed: %v", err), http.StatusInternalServerError)
return
}
log.Printf("Uploaded new proposal for %v: %v", mapName, checksum)
// Return the checksum, so the user can share their masterpiece. (They
// can calculate it anyway with md5sum, but still useful.)
fmt.Fprintf(resp, "%v", checksum)
}
// Verifies the input is MapEdits JSON. Returns the raw JSON and extracts the map name.
func validateJSON(input io.Reader) ([]byte, string, error) {
var buffer bytes.Buffer
_, err := buffer.ReadFrom(input)
if err != nil {
return nil, "", err
}
rawJson := buffer.Bytes()
// Extract the map name from the JSON
var edits mapEdits
if err := json.Unmarshal(rawJson, &edits); err != nil {
return nil, "", err
}
return rawJson, edits.Name.path(), nil
}
type mapEdits struct {
Name mapName `json:"map_name"`
// We're not going to validate the other fields
}
type mapName struct {
City cityName
MapName string `json:"map"`
}
type cityName struct {
Country string
City string
}
func (n *mapName) path() string {
return fmt.Sprintf("%v/%v/%v", n.City.Country, n.City.City, n.MapName)
}
func getLTN(resp http.ResponseWriter, req *http.Request) {
resp.Header().Set("Access-Control-Allow-Origin", "*")
values, ok := req.URL.Query()["id"]
if !ok || len(values[0]) < 1 {
http.Error(resp, "missing ID param", http.StatusBadRequest)
return
}
id := values[0]
obj := client.Bucket(bucket).Object(fmt.Sprintf("ltn_proposals/%v", id))
r, err := obj.NewReader(context.Background())
if err != nil {
http.Error(resp, fmt.Sprintf("new reader failed: %v", err), http.StatusInternalServerError)
return
}
defer r.Close()
if _, err := io.Copy(resp, r); err != nil {
http.Error(resp, fmt.Sprintf("reading failed: %v", err), http.StatusInternalServerError)
return
}
}
func createLTN(resp http.ResponseWriter, req *http.Request) {
resp.Header().Set("Access-Control-Allow-Origin", "*")
var buffer bytes.Buffer
_, err := buffer.ReadFrom(req.Body)
if err != nil {
log.Printf("Couldn't read input in createLTN call: %v", err)
http.Error(resp, err.Error(), http.StatusBadRequest)
return
}
rawBytes := buffer.Bytes()
checksum := fmt.Sprintf("%x", md5.Sum(rawBytes))
// If the proposal already exists, overwriting it with the same thing will be idempotent.
obj := client.Bucket(bucket).Object(fmt.Sprintf("ltn_proposals/%v", checksum))
w := obj.NewWriter(context.Background())
if _, err := w.Write(rawBytes); err != nil {
http.Error(resp, fmt.Sprintf("writing failed: %v", err), http.StatusInternalServerError)
return
}
if err := w.Close(); err != nil {
http.Error(resp, fmt.Sprintf("closing after write failed: %v", err), http.StatusInternalServerError)
return
}
log.Printf("Uploaded new LTN proposal: %v", checksum)
// Return the checksum, so the user can share their masterpiece. (They
// can calculate it anyway with md5sum, but still useful.)
fmt.Fprintf(resp, "%v", checksum)
}