📝 Add godocs

This commit is contained in:
Dan Jones 2024-01-22 20:08:03 -06:00
commit e736978b93
3 changed files with 31 additions and 0 deletions

View file

@ -2,8 +2,25 @@ package handler
import "github.com/gin-gonic/gin"
// This is essentially the same as [gin.HandlerFunc], but allows returning
// an error. This allows for the more idiomatic use:
//
// func UserHandler (c *gin.Context) error {
// user, err := db.GetUser(c.Get("user"))
// if err != nil {
// return err
// }
// c.JSON(200, user)
// }
type HandlerWithError func(c *gin.Context) error
// Allows you to actually use a [HandlerWithError] as a [gin.HandlerFunc].
// If an error is returned, it adds it to the context with c.Error(err).
// This needs to be handled with a middleware, such as [ErrorMiddleware]
//
// Usage:
//
// c.GET("/user", HandlerWithErrorWrapper(UserHandler))
func HandlerWithErrorWrapper(h HandlerWithError) gin.HandlerFunc {
return func(c *gin.Context) {
err := h(c)

View file

@ -7,6 +7,7 @@ import (
"github.com/gin-gonic/gin"
)
// Returns a gin middleware which writes a response with the error in the context.
func ErrorMiddleware(opts ...Option) gin.HandlerFunc {
conf := config{}
for _, opt := range opts {
@ -54,6 +55,7 @@ func ErrorMiddleware(opts ...Option) gin.HandlerFunc {
c.Set("rendered_error", re)
// @todo check a response hasn't already been sent
c.JSON(re.Status(), re)
}
}

View file

@ -12,12 +12,18 @@ type config struct {
transformers []Transformer
}
// A function which should be used to log the responded error.
type LoggerFunc func(*gin.Context, rErrors.ResponsableError)
// A function which should potentially return a [rErrors.ResponsableError] which wraps the provided error.
type Transformer func(error) rErrors.ResponsableError
// An option that customizes the behavior of [ErrorMiddleware]
type Option func(config) config
// Provides an [Option] which adds the specified [LoggerFunc] to the [ErrorMiddleware]
//
// Multiple [LoggerFunc] may be added.
func WithLogger(logger LoggerFunc) Option {
return func(c config) config {
c.loggers = append(c.loggers, logger)
@ -25,6 +31,9 @@ func WithLogger(logger LoggerFunc) Option {
}
}
// Provides an [Option] which adds the specified [Transformer] to the [ErrorMiddleware]
//
// Multiple [Transformer] may (and probably should) be added.
func WithTransformer(tr Transformer) Option {
return func(c config) config {
c.transformers = append(c.transformers, tr)
@ -32,6 +41,9 @@ func WithTransformer(tr Transformer) Option {
}
}
// Provides an [Option] which adds the default [Transformer] to the [ErrorMiddleware]
//
// This [Transformer] handles a [gin.Error].
func WithDefaultTransformer() Option {
return WithTransformer(ginTransformer)
}