-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
263 lines (231 loc) · 6.73 KB
/
main.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package main
import (
"bytes"
"flag"
"log"
"strings"
"text/template"
//"github.com/golang/glog"
"google.golang.org/genproto/googleapis/api/annotations"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/compiler/protogen"
)
var CODE_HEADER string = `
// Code generated by protoc-gen-grpc-http-client. DO NOT EDIT.
package {{.Package}}
import (
"io"
"fmt"
"strings"
"github.com/go-resty/resty/v2"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/encoding/protojson"
"github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
)
// use io module, incase generated sections don't to avoid 'import not used' error
var _ = io.EOF
func buildPath(temp httprule.Template, msg proto.Message) string {
var stack []string
for i := 0; i < len(temp.OpCodes); i += 2 {
op := utilities.OpCode(temp.OpCodes[i])
operand := temp.OpCodes[i+1]
if op == utilities.OpPush {
} else if op == utilities.OpPushM {
} else if op == utilities.OpLitPush {
stack = append(stack, temp.Pool[operand])
} else if op == utilities.OpConcatN {
n := operand
l := len(stack) - n
stack = append(stack[:l], strings.Join(stack[l:], "/"))
} else if op == utilities.OpCapture {
msg.ProtoReflect().Range(func(field protoreflect.FieldDescriptor, val protoreflect.Value) bool {
if field.JSONName() == temp.Pool[operand] {
stack = append(stack, val.String())
}
return true
})
}
}
segs := strings.Join(stack, "/")
if temp.Verb != "" {
return fmt.Sprintf("/%s:%s", segs, temp.Verb)
}
return "/" + segs
}
`
var CODE_SERVICE string = `
// {{.Service}}HttpClient connects to GRPC http gateway
type {{.Service}}HttpClient struct {
server string
client *resty.Client
}
// New{{.Service}}HttpClient creates new {{.Service}}HttpClient
func New{{.Service}}HttpClient(url string) *{{.Service}}HttpClient {
o := &{{.Service}}HttpClient{server:url, client:resty.New().SetBaseURL(url)}
return o
}
`
var CODE_METHOD string = `
func (client *{{.Service}}HttpClient) {{.Name}}(i *{{.InputType}}) (*{{.OutputType}}, error) {
// StreamingInput: {{.StreamInput}}
// StreamingOutput: {{.StreamOutput}}
// {{.HttpMethod}} {{.HttpPath}}
{{if eq .HttpMethod "POST"}}//body: {{.HttpBody}}{{end}}
{{if eq .HttpMethod "GET"}}
c, _ := httprule.Parse("{{.HttpPath}}")
path := buildPath(c.Compile(), i)
resp, err := client.client.R().Get(path)
if err != nil {
return nil, err
}
data := resp.Body()
out := {{.OutputType}}{}
err = protojson.Unmarshal(data, &out)
return &out, err
{{else if eq .HttpMethod "DELETE"}}
c, _ := httprule.Parse("{{.HttpPath}}")
path := buildPath(c.Compile(), i)
resp, err := client.client.R().Delete(path)
if err != nil {
return nil, err
}
data := resp.Body()
out := {{.OutputType}}{}
err = protojson.Unmarshal(data, &out)
return &out, err
{{else}}
return nil, nil
{{end}}
}
`
func contains(c []string, a string) bool {
for _, i := range c {
if a == i {
return true
}
}
return false
}
type headerDesc struct {
Package string
}
type serviceDesc struct {
Service string
}
type methodDesc struct {
Package string
Service string
Name string
InputType string
OutputType string
StreamOutput bool
StreamInput bool
HttpMethod string
HttpPath string
HttpBody string
}
func cleanProtoType(name string, p string) string {
if strings.HasPrefix(name, "."+p+".") {
return name[len(p)+2:]
}
return name
}
func boolPtrDefaultFalse(b *bool) bool {
if b == nil {
return false
}
return *b
}
func main() {
flag.Parse()
//defer glog.Flush()
/*
if *versionFlag {
fmt.Printf("Version %v, commit %v, built at %v\n", version, commit, date)
os.Exit(0)
}
*/
protogen.Options{
ParamFunc: flag.CommandLine.Set,
}.Run(func(gen *protogen.Plugin) error {
headerTemplate, _ := template.New("header").Parse(CODE_HEADER)
serviceTemplate, _ := template.New("service").Parse(CODE_SERVICE)
methodTemplate, _ := template.New("method").Parse(CODE_METHOD)
for _, file := range gen.Files {
log.Printf("ext: %#v", file.Extensions)
if contains(gen.Request.FileToGenerate, *file.Proto.Name) {
//log.Printf("File: %s", *file.Name)
text := bytes.NewBufferString("")
headerTemplate.Execute(text, headerDesc{Package: *file.Proto.Package})
for _, service := range file.Services {
serviceTemplate.Execute(text, serviceDesc{Service: service.GoName})
log.Printf("Service: %s", service.GoName)
for _, method := range service.Methods {
httpMethod := ""
httpPath := ""
httpBody := ""
if proto.HasExtension(method.Desc.Options(), annotations.E_Http) {
log.Printf("Has HTTP")
ext := proto.GetExtension(method.Desc.Options(), annotations.E_Http)
opts, ok := ext.(*annotations.HttpRule)
if !ok {
//return nil, fmt.Errorf("extension is %T; want an HttpRule", ext)
} else {
if p, ok := opts.Pattern.(*annotations.HttpRule_Get); ok {
httpMethod = "GET"
httpPath = p.Get
} else if p, ok := opts.Pattern.(*annotations.HttpRule_Post); ok {
httpMethod = "POST"
httpPath = p.Post
httpBody = opts.Body
} else if p, ok := opts.Pattern.(*annotations.HttpRule_Delete); ok {
httpMethod = "DELETE"
httpPath = p.Delete
} else {
log.Printf("http: %#v", opts.Pattern)
}
}
}
log.Printf(" method: %#v", method.Desc.Options().ProtoReflect().ProtoMethods())
err := methodTemplate.Execute(text, methodDesc{
Package: *file.Proto.Package,
Service: service.GoName, Name: method.GoName,
InputType: cleanProtoType(method.Input.GoIdent.GoName, *file.Proto.Package),
OutputType: cleanProtoType(method.Output.GoIdent.GoName, *file.Proto.Package),
StreamOutput: method.Desc.IsStreamingServer(),
StreamInput: method.Desc.IsStreamingClient(),
HttpMethod: httpMethod,
HttpPath: httpPath,
HttpBody: httpBody,
})
if err != nil {
log.Printf("Error: %s", err)
}
}
}
n := strings.Replace(*file.Proto.Name, ".proto", ".pb.httpclient.go", -1)
log.Printf("output: %s", n)
genFile := gen.NewGeneratedFile(n, protogen.GoImportPath(file.GoImportPath))
if _, err := genFile.Write(text.Bytes()); err != nil {
return err
}
//t := text.String()
//f := &plugin.CodeGeneratorResponse_File{Name: &n, Content: &t}
//out = append(out, f)
}
}
/*
resp := &plugin.CodeGeneratorResponse{File: out}
buf, err := proto.Marshal(resp)
if err != nil {
log.Fatal(err)
}
if _, err := os.Stdout.Write(buf); err != nil {
log.Fatal(err)
}
*/
return nil
})
}