refactor: move http api to a new transport layer
This commit is contained in:
parent
476c4b056f
commit
0448f66ab2
41 changed files with 822 additions and 390 deletions
65
internal/transport/route.go
Normal file
65
internal/transport/route.go
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
package transport
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.wzray.com/homelab/hivemind/internal/transport/codec"
|
||||
)
|
||||
|
||||
type route[In, Out any] struct {
|
||||
path string
|
||||
}
|
||||
|
||||
func NewRoute[In, Out any](path string) route[In, Out] {
|
||||
return route[In, Out]{
|
||||
path: path,
|
||||
}
|
||||
}
|
||||
|
||||
func routeToHandler[In, Out any](r route[In, Out], handler func(In) (Out, error)) Handler {
|
||||
return Handler{
|
||||
path: r.path,
|
||||
handler: func(c codec.Codec, b []byte) ([]byte, error) {
|
||||
data, err := codec.Decode[In](c, b)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to decode body: %w", err)
|
||||
}
|
||||
|
||||
out, err := handler(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error while handling request: %w", err)
|
||||
}
|
||||
|
||||
raw, err := codec.Encode(c, out)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to encode body: %w", err)
|
||||
}
|
||||
|
||||
return raw, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (e route[In, Out]) Call(caller Caller, host string, data In) (Out, error) {
|
||||
var out Out
|
||||
err := caller.Call(host, e.path, data, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (e route[In, Out]) CallNoInput(caller Caller, host string) (Out, error) {
|
||||
var out Out
|
||||
err := caller.Call(host, e.path, struct{}{}, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (e route[In, Out]) CallNoOutput(caller Caller, host string, data In) error {
|
||||
return caller.Call(host, e.path, data, nil)
|
||||
}
|
||||
|
||||
func (e route[In, Out]) Path() string {
|
||||
return e.path
|
||||
}
|
||||
|
||||
func (e route[In, Out]) Register(r Registrator, h func(In) (Out, error)) {
|
||||
r.Register(routeToHandler(e, h))
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue