|
| 1 | +# Iris Handler with Generics support |
| 2 | + |
| 3 | +```go |
| 4 | +package x |
| 5 | + |
| 6 | +import ( |
| 7 | + "github.com/kataras/iris/v12/context" |
| 8 | + "github.com/kataras/iris/v12/x/errors" |
| 9 | +) |
| 10 | + |
| 11 | +var ErrorHandler context.ErrorHandler = context.ErrorHandlerFunc(errors.InvalidArgument.Err) |
| 12 | + |
| 13 | +type ( |
| 14 | + Handler[Request any | *context.Context, Response any] func(Request) (Response, error) |
| 15 | + HandlerWithCtx[Request any, Response any] func(*context.Context, Request) (Response, error) |
| 16 | +) |
| 17 | + |
| 18 | +func HandleContext[Request any, Response any](handler HandlerWithCtx[Request, Response]) context.Handler { |
| 19 | + return func(ctx *context.Context) { |
| 20 | + var req Request |
| 21 | + if err := ctx.ReadJSON(&req); err != nil { |
| 22 | + errors.InvalidArgument.Details(ctx, "unable to parse body", err.Error()) |
| 23 | + return |
| 24 | + } |
| 25 | + |
| 26 | + resp, err := handler(ctx, req) |
| 27 | + if err != nil { |
| 28 | + ErrorHandler.HandleContextError(ctx, err) |
| 29 | + return |
| 30 | + } |
| 31 | + |
| 32 | + if _, err = ctx.JSON(resp); err != nil { |
| 33 | + errors.Internal.Details(ctx, "unable to parse response", err.Error()) |
| 34 | + return |
| 35 | + } |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +func Handle[Request any, Response any](handler Handler[Request, Response]) context.Handler { |
| 40 | + return HandleContext(func(_ *context.Context, req Request) (Response, error) { return handler(req) }) |
| 41 | +} |
| 42 | + |
| 43 | +``` |
| 44 | + |
| 45 | +Usage Code: |
| 46 | + |
| 47 | +```go |
| 48 | +import ( |
| 49 | + "github.com/kataras/iris/v12" |
| 50 | + "github.com/kataras/iris/v12/x" |
| 51 | +) |
| 52 | + |
| 53 | +type ( |
| 54 | + Req struct { |
| 55 | + Email string `json:"email"` |
| 56 | + } |
| 57 | + |
| 58 | + Res struct { |
| 59 | + Verified bool `json:"verified"` |
| 60 | + } |
| 61 | +) |
| 62 | + |
| 63 | +func main() { |
| 64 | + app := iris.New() |
| 65 | + app.Post("/", your_package.Handle(handler)) |
| 66 | + app.Listen(":8080") |
| 67 | +} |
| 68 | + |
| 69 | +func handler(req Req) (Res, error){ |
| 70 | + verified := req. Email == "[email protected]" |
| 71 | + return Res{Verified: verified}, nil |
| 72 | +} |
| 73 | +``` |
| 74 | + |
| 75 | +Example response: |
| 76 | + |
| 77 | +```json |
| 78 | +{ |
| 79 | + "verified": true |
| 80 | +} |
| 81 | +``` |
0 commit comments