-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswagger.go
More file actions
55 lines (48 loc) · 1.43 KB
/
swagger.go
File metadata and controls
55 lines (48 loc) · 1.43 KB
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
// SPDX-License-Identifier: EUPL-1.2
package api
import (
"fmt"
"sync"
"sync/atomic"
"github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/swaggo/swag"
)
// swaggerSeq provides unique instance names so multiple Engine instances
// (common in tests) do not collide in the global swag registry.
var swaggerSeq atomic.Uint64
// swaggerSpec wraps SpecBuilder to satisfy the swag.Spec interface.
// The spec is built once on first access and cached.
type swaggerSpec struct {
builder *SpecBuilder
groups []RouteGroup
once sync.Once
doc string
}
// ReadDoc returns the OpenAPI 3.1 JSON document for this spec.
func (s *swaggerSpec) ReadDoc() string {
s.once.Do(func() {
data, err := s.builder.Build(s.groups)
if err != nil {
s.doc = `{"openapi":"3.1.0","info":{"title":"error","version":"0.0.0"},"paths":{}}`
return
}
s.doc = string(data)
})
return s.doc
}
// registerSwagger mounts the Swagger UI and doc.json endpoint.
func registerSwagger(g *gin.Engine, title, description, version string, groups []RouteGroup) {
spec := &swaggerSpec{
builder: &SpecBuilder{
Title: title,
Description: description,
Version: version,
},
groups: groups,
}
name := fmt.Sprintf("swagger_%d", swaggerSeq.Add(1))
swag.Register(name, spec)
g.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.NewHandler(), ginSwagger.InstanceName(name)))
}