-
-
Notifications
You must be signed in to change notification settings - Fork 564
/
Copy pathopenapi.go
73 lines (65 loc) Β· 1.62 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
package codegen
import (
"encoding/json"
"path/filepath"
"text/template"
"gopkg.in/yaml.v2"
"goa.design/goa/codegen"
"goa.design/goa/expr"
"goa.design/goa/http/codegen/openapi"
)
// OpenAPIFiles returns the files for the OpenAPIFile spec of the given HTTP API.
func OpenAPIFiles(root *expr.RootExpr) ([]*codegen.File, error) {
// Only create a OpenAPI specification if there are HTTP services.
if len(root.API.HTTP.Services) == 0 {
return nil, nil
}
jsonPath := filepath.Join(codegen.Gendir, "http", "openapi.json")
yamlPath := filepath.Join(codegen.Gendir, "http", "openapi.yaml")
var (
jsonSection *codegen.SectionTemplate
yamlSection *codegen.SectionTemplate
)
{
spec, err := openapi.NewV2(root, root.API.Servers[0].Hosts[0])
if err != nil {
return nil, err
}
jsonSection = &codegen.SectionTemplate{
Name: "openapi",
FuncMap: template.FuncMap{"toJSON": toJSON},
Source: "{{ toJSON .}}",
Data: spec,
}
yamlSection = &codegen.SectionTemplate{
Name: "openapi",
FuncMap: template.FuncMap{"toYAML": toYAML},
Source: "{{ toYAML .}}",
Data: spec,
}
}
return []*codegen.File{
{
Path: jsonPath,
SectionTemplates: []*codegen.SectionTemplate{jsonSection},
},
{
Path: yamlPath,
SectionTemplates: []*codegen.SectionTemplate{yamlSection},
},
}, nil
}
func toJSON(d interface{}) string {
b, err := json.Marshal(d)
if err != nil {
panic("openapi: " + err.Error()) // bug
}
return string(b)
}
func toYAML(d interface{}) string {
b, err := yaml.Marshal(d)
if err != nil {
panic("openapi: " + err.Error()) // bug
}
return string(b)
}