-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathunary.go
69 lines (50 loc) · 1.29 KB
/
unary.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package rpc
import (
"bytes"
"context"
"io"
"net/http"
"github.com/alexfalkowski/go-service/errors"
"github.com/alexfalkowski/go-service/net/http/content"
)
// UnaryHandler for rpc.
type UnaryHandler[Req any, Res any] func(ctx context.Context, req *Req) (*Res, error)
// Unary for rpc.
func Unary[Req any, Res any](path string, handler UnaryHandler[Req, Res]) {
h := func(res http.ResponseWriter, req *http.Request) {
ctx := req.Context()
ctx = WithRequest(ctx, req)
ctx = WithResponse(ctx, res)
ct := content.NewFromRequest(req)
m, err := ct.Marshaller(enc)
if err != nil {
WriteError(ctx, errors.Prefix("rpc marshaller", err))
return
}
res.Header().Add(content.TypeKey, ct.Media)
body, err := io.ReadAll(req.Body)
if err != nil {
WriteError(ctx, errors.Prefix("rpc read", err))
return
}
req.Body = io.NopCloser(bytes.NewBuffer(body))
var rq Req
ptr := &rq
if err := m.Unmarshal(body, ptr); err != nil {
WriteError(ctx, errors.Prefix("rpc unmarshal", err))
return
}
rs, err := handler(ctx, ptr)
if err != nil {
WriteError(ctx, errors.Prefix("rpc handle", err))
return
}
d, err := m.Marshal(rs)
if err != nil {
WriteError(ctx, errors.Prefix("rpc marshal", err))
return
}
res.Write(d)
}
mux.HandleFunc("POST "+path, h)
}