/
example_cli.go
107 lines (94 loc) Β· 2.46 KB
/
example_cli.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package codegen
import (
"os"
"path"
"path/filepath"
"strings"
"goa.design/goa/codegen"
"goa.design/goa/codegen/example"
"goa.design/goa/expr"
)
// ExampleCLIFiles returns an example gRPC client tool implementation.
func ExampleCLIFiles(genpkg string, root *expr.RootExpr) []*codegen.File {
var files []*codegen.File
for _, svr := range root.API.Servers {
if f := exampleCLI(genpkg, root, svr); f != nil {
files = append(files, f)
}
}
return files
}
// exampleCLI returns an example client tool HTTP implementation for the given
// server expression.
func exampleCLI(genpkg string, root *expr.RootExpr, svr *expr.ServerExpr) *codegen.File {
var (
mainPath string
svrdata = example.Servers.Get(svr)
)
{
mainPath = filepath.Join("cmd", svrdata.Dir+"-cli", "grpc.go")
if _, err := os.Stat(mainPath); !os.IsNotExist(err) {
return nil // file already exists, skip it.
}
}
var (
rootPath string
apiPkg string
scope = codegen.NewNameScope()
)
{
// genpkg is created by path.Join so the separator is / regardless of operating system
idx := strings.LastIndex(genpkg, string("/"))
rootPath = "."
if idx > 0 {
rootPath = genpkg[:idx]
}
apiPkg = scope.Unique(strings.ToLower(codegen.Goify(root.API.Name, false)), "api")
}
var (
specs []*codegen.ImportSpec
)
{
specs = []*codegen.ImportSpec{
{Path: "context"},
{Path: "encoding/json"},
{Path: "flag"},
{Path: "fmt"},
{Path: "google.golang.org/grpc"},
{Path: "os"},
{Path: "time"},
{Path: "goa.design/goa"},
{Path: "goa.design/goa/grpc", Name: "goagrpc"},
{Path: rootPath, Name: apiPkg},
{Path: path.Join(genpkg, "grpc", "cli", svrdata.Dir), Name: "cli"},
}
}
var (
sections []*codegen.SectionTemplate
)
{
sections = []*codegen.SectionTemplate{
codegen.Header("", "main", specs),
&codegen.SectionTemplate{Name: "do-grpc-cli", Source: grpcCLIDoT, Data: svrdata},
}
}
return &codegen.File{Path: mainPath, SectionTemplates: sections, SkipExist: true}
}
const (
grpcCLIDoT = `func doGRPC(scheme, host string, timeout int, debug bool) (goa.Endpoint, interface{}, error) {
conn, err := grpc.Dial(host, grpc.WithInsecure())
if err != nil {
fmt.Fprintf(os.Stderr, "could not connect to gRPC server at %s: %v\n", host, err)
}
return cli.ParseEndpoint(conn)
}
{{ if eq .DefaultTransport.Type "grpc" }}
func grpcUsageCommands() string {
return cli.UsageCommands()
}
func grpcUsageExamples() string {
return cli.UsageExamples()
}
{{- end }}
`
)