-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
swagger.go
72 lines (56 loc) · 1.38 KB
/
swagger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package swag
import (
"errors"
"fmt"
"sync"
)
// Name is a unique name be used to register swag instance.
const Name = "swagger"
var (
swaggerMu sync.RWMutex
swags map[string]Swagger
)
// Swagger is an interface to read swagger document.
type Swagger interface {
ReadDoc() string
}
// Register registers swagger for given name.
func Register(name string, swagger Swagger) {
swaggerMu.Lock()
defer swaggerMu.Unlock()
if swagger == nil {
panic("swagger is nil")
}
if swags == nil {
swags = make(map[string]Swagger)
}
if _, ok := swags[name]; ok {
panic("Register called twice for swag: " + name)
}
swags[name] = swagger
}
// GetSwagger returns the swagger instance for given name.
// If not found, returns nil.
func GetSwagger(name string) Swagger {
swaggerMu.RLock()
defer swaggerMu.RUnlock()
return swags[name]
}
// ReadDoc reads swagger document. An optional name parameter can be passed to read a specific document.
// The default name is "swagger".
func ReadDoc(optionalName ...string) (string, error) {
swaggerMu.RLock()
defer swaggerMu.RUnlock()
if swags == nil {
return "", errors.New("no swag has yet been registered")
}
name := Name
if len(optionalName) != 0 && optionalName[0] != "" {
name = optionalName[0]
}
swag, ok := swags[name]
if !ok {
return "", fmt.Errorf("no swag named \"%s\" was registered", name)
}
return swag.ReadDoc(), nil
}