Skip to content

Commit

Permalink
feat: add option.DefaultResponse (#425)
Browse files Browse the repository at this point in the history
* feat: add OptionAddDefaultResponse

* Adds OptionDefaultResponse to add a default response to a route
  • Loading branch information
EwenQuim authored Feb 27, 2025
1 parent 93f50ab commit 58fcd26
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
9 changes: 9 additions & 0 deletions openapi_operations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"net/http"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -189,6 +190,14 @@ func TestWithGlobalResponseType(t *testing.T) {
routeCustom.Operation.Responses.Value("202").Value.Content.Get("application/x-yaml").Schema.Ref,
)
})

t.Run("global 'default' response", func(t *testing.T) {
route := Get(s, "/test", testController,
OptionDefaultResponse("Default response", Response{Type: HTTPError{}}),
)
assert.Equal(t, "Default response", *route.Operation.Responses.Value("default").Value.Description)
assert.Equal(t, "#/components/schemas/HTTPError", route.Operation.Responses.Value("default").Value.Content.Get("application/json").Schema.Ref)
})
})

t.Run("should be fatal", func(t *testing.T) {
Expand Down
16 changes: 16 additions & 0 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,22 @@ func OptionAddResponse(code int, description string, response Response) func(*Ba
}
}

// OptionDefaultResponse adds a default response to a route
// Required: Response.Type must be set
// Optional: Response.ContentTypes will default to `application/json` and `application/xml` if not set
func OptionDefaultResponse(description string, response Response) func(*BaseRoute) {
return func(r *BaseRoute) {
if r.Operation.Responses == nil {
r.Operation.Responses = openapi3.NewResponses()
}
r.Operation.Responses.Set(
"default", &openapi3.ResponseRef{
Value: r.OpenAPI.buildOpenapi3Response(description, response),
},
)
}
}

// OptionRequestContentType sets the accepted content types for the route.
// By default, the accepted content types is */*.
// This will override any options set at the server level.
Expand Down

0 comments on commit 58fcd26

Please sign in to comment.