-
Notifications
You must be signed in to change notification settings - Fork 0
/
server2.go
97 lines (88 loc) · 2.4 KB
/
server2.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
package main
import(
"io"
"fmt"
m "encoding/json"
"io/ioutil"
"net/http"
"github.com/julienschmidt/httprouter"
"strconv"
)
type Data struct{
Key int `json:"key"`
Value string `json:"value"`
}
type Response struct{
DataResponse []Data `json:"Response"`
}
var dataCollection []Data
func addKeys(rw http.ResponseWriter, req *http.Request , p httprouter.Params) {
fmt.Println("entering service")
var objData Data
body,_ := ioutil.ReadAll(io.LimitReader(req.Body, 1048576))
m.Unmarshal(body, &objData)
dataCollection=append(dataCollection,objData)
rw.WriteHeader(http.StatusCreated)
rw.Header().Set("Content-Type", "application/json;charset=UTF-8")
rw.WriteHeader(http.StatusCreated)
}
func findKeys(rw http.ResponseWriter, req *http.Request, p httprouter.Params){
keyId,_:=strconv.Atoi(p.ByName("key_id"))
var keyValue Data
for _,value:=range dataCollection{
if(value.Key==keyId){
keyValue=value;
break;
}
}
if(keyValue.Key==0){
rw.WriteHeader(http.StatusOK)
fmt.Fprintf(rw,"Requested keyId not found")
return
}
rw.WriteHeader(http.StatusOK)
rw.Header().Set("Content-Type", "application/json;charset=UTF-8")
if err := m.NewEncoder(rw).Encode(keyValue); err != nil {
panic(err)
}
}
func updateKey(rw http.ResponseWriter, req *http.Request, p httprouter.Params){
keyId,_:=strconv.Atoi(p.ByName("key_id"))
keyValue:=p.ByName("value")
var dataResp Data
for i,_:=range dataCollection{
objData:=&dataCollection[i]
if(objData.Key==keyId){
objData.Value=keyValue;
dataResp.Value=keyValue;
dataResp.Key=keyId;
break;
}
}
rw.WriteHeader(http.StatusOK)
rw.Header().Set("Content-Type", "application/json;charset=UTF-8")
if err := m.NewEncoder(rw).Encode(dataResp); err != nil {
panic(err)
}
}
func findAllKeys(rw http.ResponseWriter, req *http.Request, p httprouter.Params){
var response Response
response.DataResponse = dataCollection
rw.WriteHeader(http.StatusOK)
rw.Header().Set("Content-Type", "application/json;charset=UTF-8")
if err := m.NewEncoder(rw).Encode(response); err != nil {
panic(err)
}
}
func main(){
mux := httprouter.New()
mux.GET("/keys/:key_id", findKeys)
mux.POST("/keys", addKeys)
mux.GET("/keys", findAllKeys)
mux.PUT("/keys/:key_id/:value",updateKey)
server := http.Server{
Addr: ":3001",
Handler: mux,
}
server.ListenAndServe()
}