HTTP Server and Request Routing
July 13, 2025HTTP Server and Request Routing
The server handles HTTP requests and routes them to the appropriate nodes based on the hash ring.
Implementation
// shreder/server.gotype CacheServer struct { cache *Cache peers []string mu sync.Mutex selfID string hashRing *hash_ring.HashRing}
func (cs *CacheServer) SetHandler(w http.ResponseWriter, r *http.Request) { bodyBytes, err := io.ReadAll(r.Body) if err != nil { w.WriteHeader(http.StatusBadRequest) return }
var request setRequest if err := json.Unmarshal(bodyBytes, &request); err != nil { w.WriteHeader(http.StatusBadRequest) return }
isReplication := r.Header.Get(replicationHeader) == "true" targetNode := cs.hashRing.GetNode(request.Key)
if targetNode.Address == cs.selfID { cs.cache.Set(request.Key, request.Value, 10*time.Minute) if !isReplication { cs.replicaset(request.Key, request.Value) } w.WriteHeader(http.StatusOK) } else { r.Body = io.NopCloser(bytes.NewReader(bodyBytes)) cs.forwardRequest(targetNode, r, w) }}
Request Flow
- Client sends request to any node
- Node uses hash ring to determine responsible node
- If current node is responsible, it processes the request locally
- Otherwise, it forwards the request to the responsible node
- Data changes are replicated to peer nodes