| 30 | } |
| 31 | |
| 32 | func (h *httpKVAPI) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 33 | key := r.RequestURI |
| 34 | defer r.Body.Close() |
| 35 | switch r.Method { |
| 36 | case http.MethodPut: |
| 37 | v, err := io.ReadAll(r.Body) |
| 38 | if err != nil { |
| 39 | log.Printf("Failed to read on PUT (%v)\n", err) |
| 40 | http.Error(w, "Failed on PUT", http.StatusBadRequest) |
| 41 | return |
| 42 | } |
| 43 | |
| 44 | h.store.Propose(key, string(v)) |
| 45 | |
| 46 | // Optimistic-- no waiting for ack from raft. Value is not yet |
| 47 | // committed so a subsequent GET on the key may return old value |
| 48 | w.WriteHeader(http.StatusNoContent) |
| 49 | case http.MethodGet: |
| 50 | if v, ok := h.store.Lookup(key); ok { |
| 51 | w.Write([]byte(v)) |
| 52 | } else { |
| 53 | http.Error(w, "Failed to GET", http.StatusNotFound) |
| 54 | } |
| 55 | case http.MethodPost: |
| 56 | url, err := io.ReadAll(r.Body) |
| 57 | if err != nil { |
| 58 | log.Printf("Failed to read on POST (%v)\n", err) |
| 59 | http.Error(w, "Failed on POST", http.StatusBadRequest) |
| 60 | return |
| 61 | } |
| 62 | |
| 63 | nodeID, err := strconv.ParseUint(key[1:], 0, 64) |
| 64 | if err != nil { |
| 65 | log.Printf("Failed to convert ID for conf change (%v)\n", err) |
| 66 | http.Error(w, "Failed on POST", http.StatusBadRequest) |
| 67 | return |
| 68 | } |
| 69 | |
| 70 | cc := raftpb.ConfChange{ |
| 71 | Type: raftpb.ConfChangeAddNode, |
| 72 | NodeID: nodeID, |
| 73 | Context: url, |
| 74 | } |
| 75 | h.confChangeC <- cc |
| 76 | // As above, optimistic that raft will apply the conf change |
| 77 | w.WriteHeader(http.StatusNoContent) |
| 78 | case http.MethodDelete: |
| 79 | nodeID, err := strconv.ParseUint(key[1:], 0, 64) |
| 80 | if err != nil { |
| 81 | log.Printf("Failed to convert ID for conf change (%v)\n", err) |
| 82 | http.Error(w, "Failed on DELETE", http.StatusBadRequest) |
| 83 | return |
| 84 | } |
| 85 | |
| 86 | cc := raftpb.ConfChange{ |
| 87 | Type: raftpb.ConfChangeRemoveNode, |
| 88 | NodeID: nodeID, |
| 89 | } |