add x/errors.Handler, CreateHandler, NoContentHandler, NoContenetOrNotModifiedHandler and ListHandler ready-to-use handlers for service method calls to Iris Handler

This commit is contained in:
Gerasimos (Makis) Maropoulos 2024-01-09 11:11:53 +02:00
parent 7024f61a62
commit ad75479541
No known key found for this signature in database
GPG Key ID: B9839E9CD30B7B6B
7 changed files with 161 additions and 18 deletions

View File

@ -24,7 +24,7 @@ jobs:
uses: actions/checkout@v4
- name: Set up Go 1.x
uses: actions/setup-go@v4
uses: actions/setup-go@v5
with:
go-version-file: './go.mod'
check-latest: true

View File

@ -23,6 +23,7 @@ Developers are not forced to upgrade if they don't really need it. Upgrade whene
Changes apply to `main` branch.
- Add `x/errors.Handler`, `CreateHandler`, `NoContentHandler`, `NoContenetOrNotModifiedHandler` and `ListHandler` ready-to-use handlers for service method calls to Iris Handler.
- Add `x/errors.List` package-level function to support `ListObjects(ctx context.Context, opts pagination.ListOptions, f Filter) ([]Object, int64, error)` type of service calls.
- Simplify how validation errors on `/x/errors` package works. A new `x/errors/validation` sub-package added to make your life easier (using the powerful Generics feature).
- Add `x/errors.OK`, `Create`, `NoContent` and `NoContentOrNotModified` package-level generic functions as custom service method caller helpers. Example can be found [here](_examples/routing/http-wire-errors/service/main.go).

View File

@ -14,10 +14,10 @@ func main() {
app := iris.New()
service := new(myService)
app.Post("/", createHandler(service))
app.Get("/", listAllHandler(service))
app.Post("/page", listHandler(service))
app.Delete("/{id:string}", deleteHandler(service))
app.Post("/", createHandler(service)) // OR: errors.CreateHandler(service.Create)
app.Get("/", listAllHandler(service)) // OR errors.Handler(service.ListAll, errors.Value(ListRequest{}))
app.Post("/page", listHandler(service)) // OR: errors.ListHandler(service.ListPaginated)
app.Delete("/{id:string}", deleteHandler(service)) // OR: errors.NoContentOrNotModifiedHandler(service.DeleteWithFeedback, errors.PathParam[string]("id"))
app.Listen(":8080")
}
@ -59,9 +59,9 @@ func deleteHandler(service *myService) iris.Handler {
return func(ctx iris.Context) {
id := ctx.Params().Get("id")
// What it does?
// 1. Calls the service.Delete function with the given input parameter.
// 2. If the service.Delete returns an error, it sends an appropriate error response to the client.
// 3.If the service.Delete doesn't return an error then it sets the status code to 204 (No Content) and
// 1. Calls the service.DeleteWithFeedback function with the given input parameter.
// 2. If the service.DeleteWithFeedback returns an error, it sends an appropriate error response to the client.
// 3.If the service.DeleteWithFeedback doesn't return an error then it sets the status code to 204 (No Content) and
// sends the response as a JSON payload to the client.
// errors.NoContent(ctx, service.Delete, id)
// OR:

4
go.mod
View File

@ -39,9 +39,9 @@ require (
github.com/vmihailenco/msgpack/v5 v5.4.1
github.com/yosssi/ace v0.0.5
go.etcd.io/bbolt v1.3.8
golang.org/x/crypto v0.17.0
golang.org/x/crypto v0.18.0
golang.org/x/exp v0.0.0-20240103183307-be819d1f06fc
golang.org/x/net v0.19.0
golang.org/x/net v0.20.0
golang.org/x/sys v0.16.0
golang.org/x/text v0.14.0
golang.org/x/time v0.5.0

8
go.sum generated
View File

@ -271,8 +271,8 @@ golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnf
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k=
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
golang.org/x/crypto v0.18.0 h1:PGVlW0xEltQnzFZ55hkuX5+KLyrMYhHld1YHO4AKcdc=
golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg=
golang.org/x/exp v0.0.0-20240103183307-be819d1f06fc h1:ao2WRsKSzW6KuUY9IWPwWahcHCgR0s52IfwutMfEbdM=
golang.org/x/exp v0.0.0-20240103183307-be819d1f06fc/go.mod h1:iRJReGqOEeBhDZGkGbynYwcHlctCvnjTYIamk7uXpHI=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
@ -283,8 +283,8 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c=
golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U=
golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo=
golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=

View File

@ -139,6 +139,10 @@ func HandleError(ctx *context.Context, err error) bool {
return false
}
if ctx.IsStopped() {
return false
}
for errorCodeName, errorFuncs := range errorFuncCodeMap {
for _, errorFunc := range errorFuncs {
if errToSend := errorFunc(err); errToSend != nil {

View File

@ -12,7 +12,7 @@ import (
"golang.org/x/exp/constraints"
)
// Handle handles a generic response and error from a service call and sends a JSON response to the context.
// Handle handles a generic response and error from a service call and sends a JSON response to the client.
// It returns a boolean value indicating whether the handle was successful or not.
// If the error is not nil, it calls HandleError to send an appropriate error response to the client.
func Handle(ctx *context.Context, resp interface{}, err error) bool {
@ -161,7 +161,7 @@ func bindResponse[T, R any, F ResponseFunc[T, R]](ctx *context.Context, fn F, fn
return resp, !HandleError(ctx, err)
}
// OK handles a generic response and error from a service call and sends a JSON response to the context.
// OK handles a generic response and error from a service call and sends a JSON response to the client.
// It returns a boolean value indicating whether the handle was successful or not.
// If the error is not nil, it calls HandleError to send an appropriate error response to the client.
// It sets the status code to 200 (OK) and sends any response as a JSON payload.
@ -176,6 +176,88 @@ func OK[T, R any, F ResponseFunc[T, R]](ctx *context.Context, fn F, fnInput ...T
return Handle(ctx, resp, nil)
}
// HandlerInputFunc is a function which takes a context and returns a generic type T.
// It is used to call a service function with a generic type T.
// It is used for functions which do not bind a request payload.
// It is used for XHandler functions.
// Developers can design their own HandlerInputFunc functions and use them with the XHandler functions.
// To make a value required, stop the context execution through the context.StopExecution function and fire an error
// or just use one of the [InvalidArgument].X methods.
//
// See PathParam, Query and Value package-level helpers too.
type HandlerInputFunc[T any] interface {
func(ctx *context.Context) T
}
// GetRequestInputs returns a slice of generic type T from a slice of HandlerInputFunc[T].
// It is exported so end-developers can use it to get the inputs from custom HandlerInputFunc[T] functions.
func GetRequestInputs[T any, I HandlerInputFunc[T]](ctx *context.Context, fnInputFunc []I) ([]T, bool) {
inputs := make([]T, 0, len(fnInputFunc))
for _, callIn := range fnInputFunc {
if callIn == nil {
continue
}
input := callIn(ctx)
if ctx.IsStopped() { // if the input is required and it's not provided, then the context is stopped.
return nil, false
}
inputs = append(inputs, input)
}
return inputs, true
}
// PathParam returns a HandlerInputFunc which reads a path parameter from the context and returns it as a generic type T.
// It is used for XHandler functions.
func PathParam[T any, I HandlerInputFunc[T]](paramName string) I {
return func(ctx *context.Context) T {
paramValue := ctx.Params().Store.Get(paramName)
if paramValue == nil {
var t T
return t
}
return paramValue.(T)
}
}
// Value returns a HandlerInputFunc which returns a generic type T.
// It is used for XHandler functions.
func Value[T any, I HandlerInputFunc[T]](value T) I {
return func(ctx *context.Context) T {
return value
}
}
// Query returns a HandlerInputFunc which reads a URL query from the context and returns it as a generic type T.
// It is used for XHandler functions.
func Query[T any, I HandlerInputFunc[T]]() I {
return func(ctx *context.Context) T {
value, ok := ReadQuery[T](ctx)
if !ok {
var t T
return t
}
return value
}
}
// Handler handles a generic response and error from a service call and sends a JSON response to the client with status code of 200.
//
// See OK package-level function for more.
func Handler[T, R any, F ResponseFunc[T, R], I HandlerInputFunc[T]](fn F, fnInput ...I) context.Handler {
return func(ctx *context.Context) {
inputs, ok := GetRequestInputs(ctx, fnInput)
if !ok {
return
}
OK(ctx, fn, inputs...)
}
}
// ListResponseFunc is a function which takes a context,
// a pagination.ListOptions and a generic type T and returns a slice []R, total count of the items and an error.
//
@ -209,6 +291,20 @@ func List[T, R any, C constraints.Integer | constraints.Float, F ListResponseFun
return Handle(ctx, resp, nil)
}
// ListHandler handles a generic response and error from a service paginated call and sends a JSON response to the client.
//
// See List package-level function for more.
func ListHandler[T, R any, C constraints.Integer | constraints.Float, F ListResponseFunc[T, R, C], I HandlerInputFunc[T]](fn F, fnInput ...I) context.Handler {
return func(ctx *context.Context) {
inputs, ok := GetRequestInputs(ctx, fnInput)
if !ok {
return
}
List(ctx, fn, inputs...)
}
}
// Create handles a create operation and sends a JSON response with the created resource to the client.
// It returns a boolean value indicating whether the handle was successful or not.
// If the error is not nil, it calls HandleError to send an appropriate error response to the client.
@ -225,7 +321,21 @@ func Create[T, R any, F ResponseFunc[T, R]](ctx *context.Context, fn F, fnInput
return HandleCreate(ctx, resp, nil)
}
// NoContent handles a generic response and error from a service call and sends a JSON response to the context.
// CreateHandler handles a create operation and sends a JSON response with the created resource to the client with status code of 201.
//
// See Create package-level function for more.
func CreateHandler[T, R any, F ResponseFunc[T, R], I HandlerInputFunc[T]](fn F, fnInput ...I) context.Handler {
return func(ctx *context.Context) {
inputs, ok := GetRequestInputs(ctx, fnInput)
if !ok {
return
}
Create(ctx, fn, inputs...)
}
}
// NoContent handles a generic response and error from a service call and sends a JSON response to the client.
// It returns a boolean value indicating whether the handle was successful or not.
// If the error is not nil, it calls HandleError to send an appropriate error response to the client.
// It sets the status code to 204 (No Content).
@ -239,7 +349,21 @@ func NoContent[T any, F ResponseOnlyErrorFunc[T]](ctx *context.Context, fn F, fn
return NoContentOrNotModified(ctx, toFn, fnInput...)
}
// NoContent handles a generic response and error from a service call and sends a JSON response to the context.
// NoContentHandler handles a generic response and error from a service call and sends a JSON response to the client with status code of 204.
//
// See NoContent package-level function for more.
func NoContentHandler[T any, F ResponseOnlyErrorFunc[T], I HandlerInputFunc[T]](fn F, fnInput ...I) context.Handler {
return func(ctx *context.Context) {
inputs, ok := GetRequestInputs(ctx, fnInput)
if !ok {
return
}
NoContent(ctx, fn, inputs...)
}
}
// NoContent handles a generic response and error from a service call and sends a JSON response to the client.
// It returns a boolean value indicating whether the handle was successful or not.
// If the error is not nil, it calls HandleError to send an appropriate error response to the client.
// If the response is true, it sets the status code to 204 (No Content).
@ -255,6 +379,20 @@ func NoContentOrNotModified[T any, F ResponseFunc[T, bool]](ctx *context.Context
return HandleUpdate(ctx, bool(resp), nil)
}
// NoContentOrNotModifiedHandler handles a generic response and error from a service call and sends a JSON response to the client with status code of 204 or 304.
//
// See NoContentOrNotModified package-level function for more.
func NoContentOrNotModifiedHandler[T any, F ResponseFunc[T, bool], I HandlerInputFunc[T]](fn F, fnInput ...I) context.Handler {
return func(ctx *context.Context) {
inputs, ok := GetRequestInputs(ctx, fnInput)
if !ok {
return
}
NoContentOrNotModified(ctx, fn, inputs...)
}
}
// ReadPayload reads a JSON payload from the context and returns it as a generic type T.
// It also returns a boolean value indicating whether the read was successful or not.
// If the read fails, it sends an appropriate error response to the client.