Skip to content

Commit

Permalink
Merge pull request #66 from geoffreybauduin/route-tags
Browse files Browse the repository at this point in the history
feat: added a way to define route tags
  • Loading branch information
rbeuque74 authored Mar 6, 2020
2 parents 8d7e89f + 6343f72 commit cdf4844
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
8 changes: 7 additions & 1 deletion tonic/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ type Route struct {
description string
summary string
deprecated bool
tags []string

// Handler is the route handler.
handler reflect.Value
Expand Down Expand Up @@ -90,8 +91,13 @@ func (r *Route) HandlerNameWithPackage() string {

// GetTags generates a list of tags for the swagger spec
// from one route definition.
// Currently it only takes the first path of the route as the tag.
// It uses the first chunk of the path of the route as the tag
// (for example, in /foo/bar it will return the "foo" tag),
// unless specific tags have been defined with tonic.Tags
func (r *Route) GetTags() []string {
if r.tags != nil {
return r.tags
}
tags := make([]string, 0, 1)
paths := strings.SplitN(r.GetPath(), "/", 3)
if len(paths) > 1 {
Expand Down
43 changes: 43 additions & 0 deletions tonic/route_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package tonic_test

import (
"testing"

"github.com/gin-gonic/gin"
"github.com/loopfz/gadgeto/tonic"
)

func TestRoute_GetTags(t *testing.T) {
r := &tonic.Route{
RouteInfo: gin.RouteInfo{
Method: "GET",
Path: "/foo/bar",
},
}
tags := r.GetTags()
if len(tags) != 1 {
t.Fatalf("expected to have 1 tag, but got %d", len(tags))
}
if tags[0] != "foo" {
t.Fatalf("expected to have tag='foo', but got tag=%s", tags[0])
}
tonic.Tags([]string{"otherTag"})(r)
tags = r.GetTags()
if len(tags) != 1 {
t.Fatalf("expected to have 1 tag, but got %d", len(tags))
}
if tags[0] != "otherTag" {
t.Fatalf("expected to have tag='otherTag', but got tag=%s", tags[0])
}
tonic.Tags([]string{"otherTag1", "otherTag2"})(r)
tags = r.GetTags()
if len(tags) != 2 {
t.Fatalf("expected to have 2 tags, but got %d", len(tags))
}
if tags[0] != "otherTag1" {
t.Fatalf("expected to have tag='otherTag1', but got tag=%s", tags[0])
}
if tags[1] != "otherTag2" {
t.Fatalf("expected to have tag='otherTag2', but got tag=%s", tags[0])
}
}
7 changes: 7 additions & 0 deletions tonic/tonic.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,13 @@ func Deprecated(b bool) func(*Route) {
}
}

// Tags sets the tags of a route.
func Tags(tags []string) func(*Route) {
return func(r *Route) {
r.tags = tags
}
}

// BindError is an error type returned when tonic fails
// to bind parameters, to differentiate from errors returned
// by the handlers.
Expand Down

0 comments on commit cdf4844

Please sign in to comment.