Skip to content

Commit

Permalink
feat: add tags to the Server (i.e Group) level
Browse files Browse the repository at this point in the history
  • Loading branch information
dylanhitt committed Mar 21, 2024
1 parent ef7cea6 commit ca6327a
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
1 change: 1 addition & 0 deletions mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ func Register[T any, B any, Contexted ctx[B]](s *Server, method string, path str
route.operation.Summary = name
route.operation.Description = "controller: " + nameWithPath
route.operation.OperationID = fullPath + ":" + name
route.operation.Tags = append(route.operation.Tags, s.tags...)
return route
}

Expand Down
31 changes: 31 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"log/slog"
"net/http"
"os"
"slices"
"time"

"github.com/getkin/kin-openapi/openapi3"
Expand Down Expand Up @@ -45,6 +46,8 @@ type Server struct {
// For example, it allows OPTIONS /foo even if it is not declared (only GET /foo is declared).
corsMiddleware func(http.Handler) http.Handler

tags []string

middlewares []func(http.Handler) http.Handler

basePath string
Expand Down Expand Up @@ -329,3 +332,31 @@ func WithValidator(newValidator *validator.Validate) func(*Server) {
v = newValidator
}
}

// Replaces Tags for the Server (i.e Group)
// By default, the tag is the type of the response body.
func (s *Server) Tags(tags ...string) *Server {
s.tags = tags
return s
}

// AddTags adds tags from the Server (i.e Group)
// Tags from the parent Groups will be respected
func (s *Server) AddTags(tags ...string) *Server {
s.tags = append(s.tags, tags...)
return s
}

// RemoveTags removes tags from the Server (i.e Group)
// if matching tags from the parent Group will be removed
func (s *Server) RemoveTags(tags ...string) *Server {
for _, tag := range tags {
for i, t := range s.tags {
if t == tag {
s.tags = slices.Delete(s.tags, i, i+1)
break
}
}
}
return s
}
24 changes: 24 additions & 0 deletions options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,3 +271,27 @@ func TestWithPort(t *testing.T) {
require.Equal(t, "localhost:9999", s.Server.Addr)
})
}

func TestServerTags(t *testing.T) {
s := NewServer().
Tags("my-server-tag")

require.Equal(t, s.tags, []string{"my-server-tag"})
}

func TestServerAddTags(t *testing.T) {
s := NewServer().
AddTags("my-server-tag").
AddTags("my-other-server-tag")

require.Equal(t, s.tags, []string{"my-server-tag", "my-other-server-tag"})
}

func TestServerRemoveTags(t *testing.T) {
s := NewServer().
Tags("my-server-tag").
AddTags("my-other-server-tag").
RemoveTags("my-other-server-tag")

require.Equal(t, s.tags, []string{"my-server-tag"})
}

0 comments on commit ca6327a

Please sign in to comment.