-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server1.go
77 lines (70 loc) · 1.71 KB
/
Server1.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 Pair struct{
Key int
Value string
}
type PairArr struct{
Maps []Pair
}
var data = make(map[int]string)
func upd_K(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 get_K(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
key,_ := strconv.Atoi(p.ByName("key"))
pair := new(Pair)
pair.Key = key
pair.Value = data[key]
oj, err := json.Marshal(pair)
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(oj))
}
func getall_K(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
pairarr := new(PairArr)
pairarr.Maps = []Pair{}
for k, v := range data {
fmt.Println("k:", k, "v:", v)
pair := new(Pair)
pair.Key = k
pair.Value = v
pairarr.Maps = append(pairarr.Maps, *pair)
}
oj, err := json.Marshal(pairarr)
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(oj))
}
func main() {
mux := httprouter.New()
mux.PUT("/keys/:key/:value", upd_K)
mux.GET("/keys/:key", get_K)
mux.GET("/keys", getall_K)
server := http.Server{
Addr: "0.0.0.0:3000",
Handler: mux,
}
server.ListenAndServe()
}