This repository has been archived by the owner on May 30, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
openapi.go
89 lines (77 loc) · 1.92 KB
/
openapi.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package openapi3
import (
"fmt"
"net/http"
"github.com/getkin/kin-openapi/openapi3"
"goyave.dev/goyave/v4"
"goyave.dev/goyave/v4/config"
)
// Generator for OpenAPI 3 specification based on Router.
type Generator struct {
spec *openapi3.T
refs *Refs
}
// NewGenerator create a new OpenAPI 3 specification Generator.
func NewGenerator() *Generator {
return &Generator{
refs: NewRefs(),
}
}
// Generate an OpenAPI 3 specification based on the given Router.
//
// Goyave config will be loaded (if not already).
//
// The Info section is pre-filled with version 0.0.0 and the app name, fetched
// from the config.
// Servers section will be filled using the configuration as well, thanks to the
// goyave.BaseURL() function.
func (g *Generator) Generate(router *goyave.Router) *openapi3.T {
if err := loadConfig(); err != nil {
fmt.Println(err)
return nil
}
g.spec = &openapi3.T{
OpenAPI: "3.0.0",
Info: &openapi3.Info{
Title: config.GetString("app.name"),
Version: "0.0.0",
},
Paths: make(openapi3.Paths),
Servers: makeServers(),
Components: &openapi3.Components{
Schemas: make(openapi3.Schemas),
RequestBodies: make(openapi3.RequestBodies),
Responses: make(openapi3.Responses),
Parameters: make(openapi3.ParametersMap),
},
}
g.convertRouter(router)
return g.spec
}
func (g *Generator) convertRouter(router *goyave.Router) {
for _, route := range router.GetRoutes() {
NewRouteConverter(route, g.refs).Convert(g.spec)
}
for _, subrouter := range router.GetSubrouters() {
g.convertRouter(subrouter)
}
}
func loadConfig() error {
if !config.IsLoaded() {
return config.Load()
}
return nil
}
func makeServers() openapi3.Servers {
return openapi3.Servers{
&openapi3.Server{
URL: goyave.BaseURL(),
},
}
}
func canHaveBody(method string) bool {
return method == http.MethodDelete ||
method == http.MethodPatch ||
method == http.MethodPost ||
method == http.MethodPut
}