Skip to content

Commit

Permalink
Allow different names for swagger specs
Browse files Browse the repository at this point in the history
In the case where we need to include multiple docs packages in the same
process, swag.Register will fail. Despite looking like having support
for swagger specs with different names it actually does not work.

Define RegisterName and ReadDocName functions which allow you to specify
the name of the swag. Default method will still use this path but with
the 'classic' swag name of 'swagger'.
  • Loading branch information
joshk0 committed Feb 15, 2021
1 parent 3d90fc0 commit afa7d2c
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 7 deletions.
2 changes: 1 addition & 1 deletion gen/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,6 @@ func (s *s) ReadDoc() string {
}
func init() {
swag.Register(swag.Name, &s{})
swag.Register({{ printf "%q + %q" .Host .BasePath}}, &s{})
}
`
24 changes: 19 additions & 5 deletions swagger.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package swag

import (
"errors"
"fmt"
"sync"
)

Expand All @@ -10,7 +11,7 @@ const Name = "swagger"

var (
swaggerMu sync.RWMutex
swag Swagger
swags map[string]Swagger
)

// Swagger is a interface to read swagger document.
Expand All @@ -22,20 +23,33 @@ type Swagger interface {
func Register(name string, swagger Swagger) {
swaggerMu.Lock()
defer swaggerMu.Unlock()

if swagger == nil {
panic("swagger is nil")
}

if swag != nil {
if swags == nil {
swags = make(map[string]Swagger)
}

if _, ok := swags[name]; ok {
panic("Register called twice for swag: " + name)
}
swag = swagger
swags[name] = swagger
}

// ReadDoc reads swagger document.
func ReadDoc() (string, error) {
if swag != nil {
return ReadDocName(Name)
}

// ReadDocName reads swagger document with specific name.
func ReadDocName(name string) (string, error) {
if swags == nil {
return "", errors.New("no swag has yet been registered")
} else if swag, ok := swags[name]; !ok {
return "", fmt.Errorf("no swag named \"%s\" was registered", name)
} else {
return swag.ReadDoc(), nil
}
return "", errors.New("not yet registered swag")
}
2 changes: 1 addition & 1 deletion swagger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,5 +185,5 @@ func TestCalledTwicelRegister(t *testing.T) {
}

func setup() {
swag = nil
swags = make(map[string]Swagger)
}

0 comments on commit afa7d2c

Please sign in to comment.