chord/chord/httpnode/httpnode.go
2025-03-13 22:54:16 -04:00

56 lines
1.2 KiB
Go

// Package httpnode provides an implementation of a Chord client and server
// using JSON over HTTP.
package httpnode
import (
"errors"
"net/http"
"net/netip"
"github.com/go-json-experiment/json"
)
func writeOk[T any](w http.ResponseWriter, x T) {
w.Header().Set("content-type", "application/json")
r := struct {
Data T `json:"data"`
}{x}
json.MarshalWrite(w, &r)
}
func writeError(w http.ResponseWriter, status int, msg string) {
w.Header().Set("content-type", "application/json")
w.WriteHeader(status)
r := struct {
Error string `json:"error"`
}{msg}
json.MarshalWrite(w, &r)
}
func readResponse[T any](r *http.Response) (x T, err error) {
if r.StatusCode != http.StatusOK {
return x, errors.New(r.Status)
}
var b struct {
Data T `json:"data"`
Error string `json:"error"`
}
if err := json.UnmarshalRead(r.Body, &b); err != nil {
return x, err
}
if b.Error != "" {
return x, errors.New(b.Error)
}
return b.Data, nil
}
type neighbors struct {
Succ []netip.AddrPort `json:"succ"`
Pred netip.AddrPort `json:"pred,omitzero"`
}
type peervalue struct {
Peer netip.AddrPort `json:"peer"`
Value string `json:"value,omitzero"`
}