|
1 | 1 | package main
|
2 | 2 |
|
3 | 3 | import (
|
4 |
| - "encoding/json" |
5 | 4 | "fmt"
|
6 |
| - "log" |
7 | 5 | "math/rand"
|
8 |
| - "net/http" |
9 | 6 | "time"
|
10 | 7 |
|
11 | 8 | "github.com/go-redis/redis"
|
12 | 9 | )
|
13 | 10 |
|
14 |
| -type Data struct { |
15 |
| - Price string |
16 |
| - Currency string |
17 |
| - Reuse string |
18 |
| -} |
19 |
| - |
20 |
| -type Payload struct { |
21 |
| - Status string |
22 |
| - Key string |
23 |
| - Value Data |
24 |
| -} |
25 |
| - |
26 | 11 | func init() {
|
27 | 12 | NewClient()
|
28 | 13 | rand.Seed(time.Now().UnixNano())
|
@@ -50,66 +35,6 @@ func NewClient() {
|
50 | 35 | fmt.Println(pong, err)
|
51 | 36 | }
|
52 | 37 |
|
53 |
| -func homePage(w http.ResponseWriter, r *http.Request) { |
54 |
| - var m Payload |
55 |
| - m.Status = "OK" |
56 |
| - b, _ := json.Marshal(m) |
57 |
| - |
58 |
| - w.Header().Set("Content-Type", "application/json") |
59 |
| - |
60 |
| - fmt.Fprintf(w, string(b)) |
61 |
| -} |
62 |
| - |
63 |
| -func save(w http.ResponseWriter, r *http.Request) { |
64 |
| - data := Data{r.PostFormValue("price"), r.PostFormValue("currency"), r.PostFormValue("reuse")} |
65 |
| - key := RandStringRunes(13) |
66 |
| - dataToStr, _ := json.Marshal(data) |
67 |
| - err := client.Set(key, string(dataToStr), 0).Err() |
68 |
| - if err != nil { |
69 |
| - panic(err) |
70 |
| - } |
71 |
| - |
72 |
| - resPayload := Payload{"OK", string(key), data} |
73 |
| - |
74 |
| - res, err := json.Marshal(resPayload) |
75 |
| - |
76 |
| - w.Header().Set("Content-Type", "application/json") |
77 |
| - fmt.Fprintf(w, string(res)) |
78 |
| -} |
79 |
| - |
80 |
| -func load(w http.ResponseWriter, r *http.Request) { |
81 |
| - key := r.PostFormValue("key") |
82 |
| - val, err := client.Get(key).Result() |
83 |
| - var data Data |
84 |
| - |
85 |
| - resPayload := Payload{Key: key} |
86 |
| - if err == redis.Nil { |
87 |
| - resPayload.Status = "NOT_FOUND" |
88 |
| - } else if err != nil { |
89 |
| - resPayload.Status = "INTERNAL_SERVER_ERROR" |
90 |
| - } else { |
91 |
| - error := json.Unmarshal([]byte(val), &data) |
92 |
| - if error != nil { |
93 |
| - panic(error) |
94 |
| - } |
95 |
| - resPayload.Value = data |
96 |
| - resPayload.Status = "OK" |
97 |
| - |
98 |
| - } |
99 |
| - res, err := json.Marshal(resPayload) |
100 |
| - w.Header().Set("Content-Type", "application/json") |
101 |
| - fmt.Fprintf(w, string(res)) |
102 |
| - |
103 |
| -} |
104 |
| - |
105 |
| -func handleRequests() { |
106 |
| - http.HandleFunc("/", homePage) |
107 |
| - http.HandleFunc("/save", save) |
108 |
| - http.HandleFunc("/load", load) |
109 |
| - fmt.Println("Listen and serve on PORT 8081") |
110 |
| - log.Fatal(http.ListenAndServe(":8081", nil)) |
111 |
| -} |
112 |
| - |
113 | 38 | func main() {
|
114 | 39 | handleRequests()
|
115 | 40 | }
|
0 commit comments