add a new _proposals folder and a silly idea

This commit is contained in:
Gerasimos (Makis) Maropoulos 2022-04-10 01:08:11 +03:00
parent 60bf26eab8
commit b0ccd579af
No known key found for this signature in database
GPG Key ID: 66FCC29BD385FCA6
3 changed files with 94 additions and 5 deletions

View File

@ -13,4 +13,4 @@ name = "go"
enabled = true
[analyzers.meta]
import_paths = ["github.com/kataras/iris"]
import_paths = ["github.com/kataras/iris/v12"]

View File

@ -0,0 +1,81 @@
# Iris Handler with Generics support
```go
package x
import (
"github.com/kataras/iris/v12/context"
"github.com/kataras/iris/v12/x/errors"
)
var ErrorHandler context.ErrorHandler = context.ErrorHandlerFunc(errors.InvalidArgument.Err)
type (
Handler[Request any | *context.Context, Response any] func(Request) (Response, error)
HandlerWithCtx[Request any, Response any] func(*context.Context, Request) (Response, error)
)
func HandleContext[Request any, Response any](handler HandlerWithCtx[Request, Response]) context.Handler {
return func(ctx *context.Context) {
var req Request
if err := ctx.ReadJSON(&req); err != nil {
errors.InvalidArgument.Details(ctx, "unable to parse body", err.Error())
return
}
resp, err := handler(ctx, req)
if err != nil {
ErrorHandler.HandleContextError(ctx, err)
return
}
if _, err = ctx.JSON(resp); err != nil {
errors.Internal.Details(ctx, "unable to parse response", err.Error())
return
}
}
}
func Handle[Request any, Response any](handler Handler[Request, Response]) context.Handler {
return HandleContext(func(_ *context.Context, req Request) (Response, error) { return handler(req) })
}
```
Usage Code:
```go
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/x"
)
type (
Req struct {
Email string `json:"email"`
}
Res struct {
Verified bool `json:"verified"`
}
)
func main() {
app := iris.New()
app.Post("/", your_package.Handle(handler))
app.Listen(":8080")
}
func handler(req Req) (Res, error){
verified := req.Email == "iris-go@outlook.com"
return Res{Verified: verified}, nil
}
```
Example response:
```json
{
"verified": true
}
```

View File

@ -3793,10 +3793,18 @@ type JSON struct {
ErrorHandler ErrorHandler
}
// ErrorHandler describes a context error handler. As for today this is only used
// to globally or per-party or per-route handle JSON writes error.
type ErrorHandler interface {
HandleContextError(ctx *Context, err error)
type (
// ErrorHandler describes a context error handler. As for today this is only used
// to globally or per-party or per-route handle JSON writes error.
ErrorHandler interface {
HandleContextError(ctx *Context, err error)
}
// ErrorHandlerFunc a function shortcut for ErrorHandler interface.
ErrorHandlerFunc func(ctx *Context, err error)
)
func (h ErrorHandlerFunc) HandleContextError(ctx *Context, err error) {
h(ctx, err)
}
// IsDefault reports whether this JSON options structure holds the default values.