PostHandler 支持http进行Post
(w http.ResponseWriter, r *http.Request)
| 87 | |
| 88 | // PostHandler 支持http进行Post |
| 89 | func (hs *HttpHandler) PostHandler(w http.ResponseWriter, r *http.Request) { |
| 90 | type PostRequest struct { |
| 91 | Key string `json:"key"` |
| 92 | Value string `json:"value"` |
| 93 | } |
| 94 | |
| 95 | var postReq PostRequest |
| 96 | err := json.NewDecoder(r.Body).Decode(&postReq) |
| 97 | if err != nil { |
| 98 | http.Error(w, err.Error(), http.StatusBadRequest) |
| 99 | return |
| 100 | } |
| 101 | defer func(Body io.ReadCloser) { |
| 102 | err := Body.Close() |
| 103 | if err != nil { |
| 104 | |
| 105 | } |
| 106 | }(r.Body) |
| 107 | |
| 108 | if postReq.Key == "" { |
| 109 | http.Error(w, "key is empty", http.StatusBadRequest) |
| 110 | return |
| 111 | } |
| 112 | if postReq.Value == "" { |
| 113 | http.Error(w, "value is empty", http.StatusBadRequest) |
| 114 | return |
| 115 | } |
| 116 | |
| 117 | err = hs.Put([]byte(postReq.Key), []byte(postReq.Value)) |
| 118 | if err != nil { |
| 119 | http.Error(w, err.Error(), http.StatusInternalServerError) |
| 120 | return |
| 121 | } |
| 122 | |
| 123 | _, err = w.Write([]byte("ok")) |
| 124 | if err != nil { |
| 125 | // 处理写入响应失败的错误 |
| 126 | http.Error(w, err.Error(), http.StatusInternalServerError) |
| 127 | return |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | // GetListKeysHandler 支持http获取数据库中所有键 |
| 132 | func (hs *HttpHandler) GetListKeysHandler(w http.ResponseWriter, r *http.Request) { |