This repository has been archived by the owner on May 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
80 lines (63 loc) · 1.67 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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"time"
)
var PORT = os.Getenv("PORT")
type JSONResult map[string][]map[string]string
func File2GoMap(path string) JSONResult {
result := make(JSONResult)
jsonFile, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
return nil
}
json.Unmarshal(jsonFile, &result)
return result
}
func main() {
level := map[string]JSONResult{
"n5": File2GoMap("./data/n5.json"),
"n4": File2GoMap("./data/n5.json"),
}
rand.Seed(time.Now().UnixNano())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
w.Header().Set("Access-Control-Allow-Origin", "*")
fmt.Fprintf(w, "Hello 世界!")
})
http.HandleFunc("/api/all", func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
w.Header().Set("Access-Control-Allow-Origin", "*")
u := r.URL.Query()
jsonResp, err := json.Marshal(level[u.Get("level")])
if err != nil {
log.Fatal(err)
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, string(jsonResp))
})
http.HandleFunc("/api/rand", func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
w.Header().Set("Access-Control-Allow-Origin", "*")
u := r.URL.Query()
randIdx := rand.Intn(len(level[u.Get("level")]["data"]))
data := map[string]map[string]string{
"data": level[u.Get("level")]["data"][randIdx],
}
jsonResp, err := json.Marshal(data)
if err != nil {
log.Fatal(err)
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, string(jsonResp))
})
log.Println("Server started on port: " + PORT)
log.Fatal(http.ListenAndServe(":"+PORT, nil))
}