/
Server3000.go
77 lines (70 loc) · 1.85 KB
/
Server3000.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
package main
import (
"fmt"
"httprouter"
"net/http"
"encoding/json"
// "log"
"strconv"
)
type MapData struct{
Key int
Value string
}
type MapDataArray struct{
Maps []MapData
}
var data = make(map[int]string)
func updateMap(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
key,_ := strconv.Atoi(p.ByName("key"))
value := p.ByName("value")
data[key] = value
rw.WriteHeader(http.StatusCreated)
fmt.Fprint(rw, "200")
}
func getMapData(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
key,_ := strconv.Atoi(p.ByName("key"))
mapData := new(MapData)
mapData.Key = key
mapData.Value = data[key]
outgoingJSON, err := json.Marshal(mapData)
if err != nil {
//log.Println(error.Error())
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(http.StatusCreated)
fmt.Fprint(rw, string(outgoingJSON))
}
func getAllMapData(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
mapDataArray := new(MapDataArray)
mapDataArray.Maps = []MapData{}
for k, v := range data {
fmt.Println("k:", k, "v:", v)
mapData := new(MapData)
mapData.Key = k
mapData.Value = v
mapDataArray.Maps = append(mapDataArray.Maps, *mapData)
}
outgoingJSON, err := json.Marshal(mapDataArray)
if err != nil {
//log.Println(error.Error())
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(http.StatusCreated)
fmt.Fprint(rw, string(outgoingJSON))
}
func main() {
mux := httprouter.New()
mux.PUT("/keys/:key/:value", updateMap)
mux.GET("/keys/:key", getMapData)
mux.GET("/keys", getAllMapData)
server := http.Server{
Addr: "0.0.0.0:3000",
Handler: mux,
}
server.ListenAndServe()
}