-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
116 lines (87 loc) · 1.87 KB
/
api.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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
)
type reswr = http.ResponseWriter
type req = *http.Request
var _ID string
func wrp(h func(req) (string)) func(reswr, req) {
_ID = ""
return func(w reswr, r req) {
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:9876")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
w.Header().Set("Content-Type", "application/json")
switch r.Method {
case "OPTIONS":
w.Header().Set("Allow", "GET")
case "GET":
send(h(r), w)
}
}
}
func eq(s string, r req) (ok bool) {
q := r.URL.Query()
if q[s] != nil && strings.HasPrefix(q[s][0], "eq.") {
_ID = q[s][0][3:]
ok = true
}
return
}
func send(f string, w reswr) string {
w.Header().Set("Content-Type", "application/octet-stream")
file, err := os.Open(path + "/data/" + f)
if err != nil {
http.Error(w, "Could not open file "+f, 404)
}
bytes, _ := ioutil.ReadAll(file)
w.Write(bytes)
return string(bytes)
}
func geographies(r req) (s string) {
if eq("id", r) {
s = "geographies/"+_ID
} else {
s = "geographies/all.json"
}
return
}
func boundaries(r req) (s string) {
if eq("geography_id", r) {
s = "boundaries/"+_ID
}
return
}
func datasets(r req) (s string) {
if eq("id", r) {
s = "datasets/"+_ID
}
if eq("geography_id", r) {
s = "datasets/"+_ID
}
return
}
func files(r req) (s string) {
url := r.URL.String()
ss := strings.Split(url, "/")
s = "files/"+ss[len(ss)-1]
return
}
func flags(r req) (s string) {
if eq("name", r) {
s = "files/"+_ID+"-flag.svg"
}
return
}
func api() {
mux := http.NewServeMux()
mux.HandleFunc("/geographies", wrp(geographies))
mux.HandleFunc("/datasets", wrp(datasets))
mux.HandleFunc("/files/", wrp(files))
mux.HandleFunc("/flags", wrp(flags))
fmt.Println("Running API on localhost"+apiport)
http.ListenAndServe(apiport, mux)
}