1
0
Fork 0

refactor: move http api to a new transport layer

This commit is contained in:
Arthur K. 2026-01-23 09:56:01 +03:00
parent 476c4b056f
commit 0448f66ab2
Signed by: wzray
GPG key ID: B97F30FDC4636357
41 changed files with 822 additions and 390 deletions

View file

@ -5,7 +5,8 @@ import (
"io"
"net/http"
"git.wzray.com/homelab/hivemind/internal/types"
"git.wzray.com/homelab/hivemind/internal/transport"
"git.wzray.com/homelab/hivemind/internal/transport/codec"
"git.wzray.com/homelab/hivemind/internal/web/middleware"
"github.com/rs/zerolog/log"
)
@ -15,7 +16,7 @@ type Server struct {
httpServer http.Server
}
func NewServer(addr string, middleware middleware.Middleware) *Server {
func New(addr string, middleware middleware.Middleware) *Server {
mux := http.NewServeMux()
s := &Server{
mux: mux,
@ -35,7 +36,7 @@ func (s *Server) Shutdown(ctx context.Context) error {
return s.httpServer.Shutdown(ctx)
}
func (s *Server) handleFunc(route types.Route) func(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleFunc(route transport.Handler) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
log.Debug(). // TODO: make this a middleware
Str("method", r.Method).
@ -46,35 +47,36 @@ func (s *Server) handleFunc(route types.Route) func(w http.ResponseWriter, r *ht
w.Header().Set("Content-Type", "application/json; charset=utf-8")
body, err := io.ReadAll(r.Body)
raw, err := io.ReadAll(r.Body)
if err != nil {
w.Write(fail("read request body: %v", err))
log.Err(err).Msg("unable to read request body")
return
}
raw, err := route.Handle(body)
resp, err := route.Handle(codec.JSON, raw)
if err != nil {
w.Write(fail("handle request: %v", err))
log.Err(err).Msg("unable to handle request")
return
}
data, err := ok(raw)
payload, err := ok(resp)
if err != nil {
w.Write(fail("marshal response: %v", err))
log.Err(err).Msg("unable to marshal response")
return
}
w.Write(data)
w.Write(payload)
}
}
func (s *Server) Register(endpoint types.Route) {
func (s *Server) Register(endpoint transport.Handler) {
s.mux.HandleFunc(endpoint.Path(), s.handleFunc(endpoint))
}
// TODO: i don't think that I need this?
func (s *Server) RegisterRaw(method string, pattern string, handler func(http.ResponseWriter, *http.Request)) {
s.mux.HandleFunc(method+" "+pattern, handler)
}

View file

@ -4,20 +4,20 @@ import (
"encoding/json"
"fmt"
"git.wzray.com/homelab/hivemind/internal/types"
"git.wzray.com/homelab/hivemind/internal/web"
)
func fail(format string, a ...any) []byte {
r, _ := json.Marshal(types.Response[string]{
r, _ := json.Marshal(web.Response[string]{
Ok: false,
Err: fmt.Sprintf(format, a...),
})
return r
}
func ok[T any](data T) ([]byte, error) {
return json.Marshal(types.Response[T]{
func ok(data []byte) ([]byte, error) {
return json.Marshal(web.Response[json.RawMessage]{
Ok: true,
Data: data,
Data: json.RawMessage(data),
})
}