feat: add wrapper supporting no request params
This commit is contained in:
parent
c39fcbc6a1
commit
40ab2c6e61
2 changed files with 19 additions and 0 deletions
|
@ -79,6 +79,7 @@ func main() {
|
||||||
|
|
||||||
s.Register("multiply", rpc.H(Multiply))
|
s.Register("multiply", rpc.H(Multiply))
|
||||||
s.Register("divide", rpc.H(Divide))
|
s.Register("divide", rpc.H(Divide))
|
||||||
|
s.Register("hello", rpc.HS(Hello))
|
||||||
|
|
||||||
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
|
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
@ -102,6 +103,10 @@ func Divide(ctx context.Context, args *Args) (*Quotient, error) {
|
||||||
return quo, nil
|
return quo, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Hello(ctx context.Context) (string, error) {
|
||||||
|
return "world", nil
|
||||||
|
}
|
||||||
|
|
||||||
type Args struct {
|
type Args struct {
|
||||||
A int `json:"a"`
|
A int `json:"a"`
|
||||||
B int `json:"b"`
|
B int `json:"b"`
|
||||||
|
|
|
@ -41,4 +41,18 @@ func H[RQ any, RS any](handler func(context.Context, *RQ) (RS, error)) HandlerFu
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// HS is a simple generic wrapper for rpc handlers without any request params.
|
||||||
|
func HS[RS any](handler func(context.Context) (RS, error)) HandlerFunc {
|
||||||
|
return func(ctx context.Context, in json.RawMessage) (json.RawMessage, error) {
|
||||||
|
resp, err := handler(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, Error{
|
||||||
|
Code: ErrUser,
|
||||||
|
Message: err.Error(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return json.Marshal(resp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type HandlerFunc func(context.Context, json.RawMessage) (json.RawMessage, error)
|
type HandlerFunc func(context.Context, json.RawMessage) (json.RawMessage, error)
|
||||||
|
|
Loading…
Reference in a new issue