diff --git a/examples/gin-compat/main.go b/examples/gin-compat/main.go index 365071a9..01c136ee 100644 --- a/examples/gin-compat/main.go +++ b/examples/gin-compat/main.go @@ -2,6 +2,7 @@ package main import ( "context" + "errors" "fmt" "strings" @@ -90,9 +91,14 @@ func (h *HelloRequest) InTransform(ctx context.Context) error { // Transformation h.Word = strings.ToLower(h.Word) - // Custom validation + // Custom validation, with fuego provided error if h.Word == "apple" { - return fuego.BadRequestError{Title: "Please don't use the word 'apple'"} + return fuego.BadRequestError{Title: "Word not allowed", Err: errors.New("forbidden word"), Detail: "The word 'apple' is not allowed"} + } + + // Custom validation, with basic error + if h.Word == "banana" { + return errors.New("banana is not allowed") } // Context-based transformation diff --git a/extra/fuegogin/context.go b/extra/fuegogin/context.go index 933a03aa..f727d9f7 100644 --- a/extra/fuegogin/context.go +++ b/extra/fuegogin/context.go @@ -2,6 +2,7 @@ package fuegogin import ( "context" + "errors" "net/http" "strings" @@ -102,12 +103,27 @@ func (c ginContext[B]) SetStatus(code int) { } func (c ginContext[B]) Serialize(data any) error { - c.ginCtx.JSON(http.StatusOK, data) + if c.DefaultStatusCode == 0 { + c.DefaultStatusCode = http.StatusOK + } + status := c.ginCtx.Writer.Status() + if status == 0 { + status = c.DefaultStatusCode + } + if status == 0 { + status = 200 + } + c.ginCtx.JSON(status, data) return nil } func (c ginContext[B]) SerializeError(err error) { - c.ginCtx.JSON(http.StatusInternalServerError, err) + statusCode := http.StatusInternalServerError + var errorWithStatusCode fuego.ErrorWithStatus + if errors.As(err, &errorWithStatusCode) { + statusCode = errorWithStatusCode.StatusCode() + } + c.ginCtx.JSON(statusCode, err) } func (c ginContext[B]) SetDefaultStatusCode() {