/
server3.go
109 lines (81 loc) · 2.12 KB
/
server3.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
package main
import (
// Standard library packages
"encoding/json"
"fmt"
"net/http"
"strconv"
// Third party packages
"github.com/julienschmidt/httprouter"
)
type Data struct {
Key int `json:"key"`
Value string `json:"value"`
}
var Resp map[int]string
func updateKey(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
// Stub an user to be populated from the body
fmt.Println("putting data")
id := p.ByName("id")
value := p.ByName("value")
i, _ := strconv.Atoi(id)
/*u := Data{}
u.Key = i
u.Value = value*/
fmt.Println(i)
Resp[i] = value
// Write content-type, statuscode, payload
//w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
//fmt.Fprintf(w, "%s", uj)
}
func readKey(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
// Simply write some test data for now
fmt.Println("reading values")
id := p.ByName("id")
i, _ := strconv.Atoi(id)
u := Data{}
if val, ok := Resp[i]; ok {
fmt.Println(i, val)
u.Key = i
u.Value = val
}
// Marshal provided interface into JSON structure
fmt.Println("before marshalling map :", u)
uj, _ := json.Marshal(u)
fmt.Println("after marshalling map :", u)
// Write content-type, statuscode, payload
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "%s", uj)
}
func readAll(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
// Simply write some test data for now
fmt.Println("reading values")
l := len(Resp)
dataArr := make([]Data, l)
i := 0
for k, v := range Resp {
dataArr[i].Key = k
dataArr[i].Value = v
i++
}
// Marshal provided interface into JSON structure
uj, _ := json.Marshal(dataArr)
// Write content-type, statuscode, payload
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "%s", uj)
}
func main() {
// Instantiate a new router
r := httprouter.New()
Resp = make(map[int]string)
// Add a handler on /test
r.GET("/keys/:id", readKey)
r.GET("/keys", readAll)
r.PUT("/keys/:id/:value", updateKey)
// r.DELETE("/user/:id", deleteUser)
// Fire up the server
http.ListenAndServe("localhost:3002", r)
}