Skip to content

Commit

Permalink
Serialize and deserialize from gin correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
EwenQuim committed Dec 26, 2024
1 parent 4a6c6e1 commit b66dfc2
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
10 changes: 8 additions & 2 deletions examples/gin-compat/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"errors"
"fmt"
"strings"

Expand Down Expand Up @@ -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
Expand Down
20 changes: 18 additions & 2 deletions extra/fuegogin/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package fuegogin

import (
"context"
"errors"
"net/http"
"strings"

Expand Down Expand Up @@ -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() {
Expand Down

0 comments on commit b66dfc2

Please sign in to comment.