move k/v store to nodes
Forgot that nodes have to own their data to implement leaving.
This commit is contained in:
parent
ad0015a2be
commit
9c49d89637
@ -25,6 +25,9 @@ type Node struct {
|
||||
succ []Peer
|
||||
// fingers is the node's finger table.
|
||||
fingers []Peer
|
||||
|
||||
// data is the data the node owns.
|
||||
data map[ID]string
|
||||
}
|
||||
|
||||
func (n *Node) Self() Peer {
|
||||
@ -82,6 +85,21 @@ func (n *Node) Closest(id ID) Peer {
|
||||
return n.self
|
||||
}
|
||||
|
||||
// Get obtains the value for a key owned by the node.
|
||||
func (n *Node) Get(k ID) (v string, found bool) {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
v, found = n.data[k]
|
||||
return v, found
|
||||
}
|
||||
|
||||
// Set sets the value for a key.
|
||||
func (n *Node) Set(k ID, v string) {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
n.data[k] = v
|
||||
}
|
||||
|
||||
// Peer is the ID and address of a node.
|
||||
type Peer struct {
|
||||
id ID
|
||||
|
@ -1,68 +0,0 @@
|
||||
// Package store implements a synchronous in-memory K/V store
|
||||
// fronted by an HTTP server.
|
||||
package store
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Map struct {
|
||||
m sync.Map
|
||||
}
|
||||
|
||||
func New(from map[string]string) *Map {
|
||||
var m Map
|
||||
for k, v := range from {
|
||||
m.Set(k, v)
|
||||
}
|
||||
return &m
|
||||
}
|
||||
|
||||
func (m *Map) Get(k string) (string, bool) {
|
||||
r, ok := m.m.Load(k)
|
||||
return r.(string), ok
|
||||
}
|
||||
|
||||
func (m *Map) Set(k, v string) {
|
||||
m.m.Store(k, v)
|
||||
}
|
||||
|
||||
func (m *Map) Delete(k string) {
|
||||
m.m.Delete(k)
|
||||
}
|
||||
|
||||
func (m *Map) Router() http.Handler {
|
||||
r := http.NewServeMux()
|
||||
r.HandleFunc("GET /{key}", m.get)
|
||||
r.HandleFunc("PUT /{key}", m.set)
|
||||
r.HandleFunc("POST /{key}", m.set)
|
||||
r.HandleFunc("DELETE /{key}", m.delete)
|
||||
return r
|
||||
}
|
||||
|
||||
func (m *Map) get(w http.ResponseWriter, r *http.Request) {
|
||||
k := r.PathValue("key")
|
||||
v, ok := m.Get(k)
|
||||
if !ok {
|
||||
http.Error(w, "not found", http.StatusNotFound)
|
||||
}
|
||||
io.WriteString(w, v)
|
||||
}
|
||||
|
||||
func (m *Map) set(w http.ResponseWriter, r *http.Request) {
|
||||
k := r.PathValue("key")
|
||||
b, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
}
|
||||
m.Set(k, string(b))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (m *Map) delete(w http.ResponseWriter, r *http.Request) {
|
||||
k := r.PathValue("key")
|
||||
m.Delete(k)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
Loading…
Reference in New Issue
Block a user