Skip to content

Commit

Permalink
Hide route from OpenAPI spec, variadic options way
Browse files Browse the repository at this point in the history
  • Loading branch information
EwenQuim committed Oct 2, 2024
1 parent 6c7cdd9 commit f386d4f
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
3 changes: 2 additions & 1 deletion mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ type BaseRoute struct {
Params map[string]OpenAPIParam
Middlewares []func(http.Handler) http.Handler
AcceptedContentTypes []string // Content types accepted for the request body. If nil, all content types (*/*) are accepted.
Hidden bool // If true, the route will not be documented in the OpenAPI spec

MainRouter *Server // PRIVATE ref to the main router, used to register the route in the OpenAPI spec
}
Expand Down Expand Up @@ -101,7 +102,7 @@ func Register[T, B any](s *Server, route Route[T, B], controller http.Handler, o
allMiddlewares := append(s.middlewares, route.Middlewares...)
s.Mux.Handle(fullPath, withMiddlewares(route.Handler, allMiddlewares...))

if s.DisableOpenapi || route.Method == "" {
if s.DisableOpenapi || route.Hidden || route.Method == "" {
return &route
}

Expand Down
7 changes: 7 additions & 0 deletions option/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,3 +242,10 @@ func RequestContentType(consumes ...string) func(*fuego.BaseRoute) {
r.AcceptedContentTypes = consumes
}
}

// Hide hides the route from the OpenAPI spec.
func Hide() func(*fuego.BaseRoute) {
return func(r *fuego.BaseRoute) {
r.Hidden = true
}
}
33 changes: 33 additions & 0 deletions option/option_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -353,3 +353,36 @@ func TestAddError(t *testing.T) {
require.Equal(t, "Conflict: Pet with the same name already exists", *route.Operation.Responses.Value("409").Value.Description)
})
}

func TestHide(t *testing.T) {
s := fuego.NewServer()

fuego.Get(s, "/hidden", helloWorld, Hide())
fuego.Get(s, "/visible", helloWorld)

spec := s.OutputOpenAPISpec()
pathItemVisible := spec.Paths.Find("/visible")
require.NotNil(t, pathItemVisible)
pathItemHidden := spec.Paths.Find("/hidden")
require.Nil(t, pathItemHidden)

t.Run("visible route works normally", func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/visible", nil)
w := httptest.NewRecorder()

s.Mux.ServeHTTP(w, r)

require.Equal(t, 200, w.Code)
require.Equal(t, "hello world", w.Body.String())
})

t.Run("hidden route still accessible even if not in openAPI spec", func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/hidden", nil)
w := httptest.NewRecorder()

s.Mux.ServeHTTP(w, r)

require.Equal(t, 200, w.Code)
require.Equal(t, "hello world", w.Body.String())
})
}

0 comments on commit f386d4f

Please sign in to comment.