-
Notifications
You must be signed in to change notification settings - Fork 6
/
microweb.go
332 lines (277 loc) · 8.68 KB
/
microweb.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package main
import (
"strings"
"text/template"
"github.com/golang/protobuf/proto"
pgs "github.com/lyft/protoc-gen-star"
pgsgo "github.com/lyft/protoc-gen-star/lang/go"
"google.golang.org/genproto/googleapis/api/annotations"
)
type handler struct {
method string
pattern string
body string
}
type MicroWebModule struct {
*pgs.ModuleBase
ctx pgsgo.Context
tpl *template.Template
eimp map[pgs.FilePath]string // map[importPath] = alias
pconv map[pgs.FilePath]pgs.FilePath // convert paths, mostly for google imports
}
func MicroWeb() *MicroWebModule {
return &MicroWebModule{
ModuleBase: &pgs.ModuleBase{},
}
}
func (p *MicroWebModule) InitContext(ctx pgs.BuildContext) {
p.ModuleBase.InitContext(ctx)
p.ctx = pgsgo.InitContext(ctx.Parameters())
tpl := template.New("microweb").Funcs(map[string]interface{}{
"package": p.ctx.PackageName,
"name": p.ctx.Name,
"importPath": p.ctx.ImportPath,
"marshaler": p.marshaler,
"unmarshaler": p.unmarshaler,
"handlerPrefix": p.handlerPrefix,
"handlerMethod": p.handlerMethod,
"handlerPattern": p.handlerPattern,
"handlerBody": p.handlerBody,
"extraImports": p.extraImports,
"getExtraImportAlias": p.getExtraImportAlias,
})
p.eimp = make(map[pgs.FilePath]string)
p.pconv = map[pgs.FilePath]pgs.FilePath{
"google.golang.org/protobuf/types/known/emptypb": "github.com/golang/protobuf/ptypes/empty",
}
p.tpl = template.Must(tpl.Parse(microwebTpl))
}
// Name satisfies the generator.Plugin interface.
func (p *MicroWebModule) Name() string {
return "web"
}
func (p *MicroWebModule) Execute(targets map[string]pgs.File, pkgs map[string]pgs.Package) []pgs.Artifact {
ignored_packages := map[string]bool{}
params := p.ctx.Params()
if value, ok := params["ignore_packages"]; ok {
for _, ignored_pkg := range strings.Split(value, ";") {
ignored_packages[ignored_pkg] = true
}
}
for _, t := range targets {
packageName := t.Package().ProtoName().String()
fileName := t.Name().String()
if !ignored_packages[packageName] {
p.generate(t)
} else {
p.Debugf("Ignoring filename %s because it belongs to the ignored package %s", fileName, packageName)
}
}
return p.Artifacts()
}
func getHandler(m pgs.Method) *handler {
opts := m.Descriptor().GetOptions()
pext, _ := proto.GetExtension(opts, annotations.E_Http)
ext, ok := pext.(*annotations.HttpRule)
if !ok {
return nil
}
switch {
case ext.GetGet() != "":
return &handler{method: "GET", pattern: ext.GetGet(), body: ext.GetBody()}
case ext.GetPost() != "":
return &handler{method: "POST", pattern: ext.GetPost(), body: ext.GetBody()}
case ext.GetPut() != "":
return &handler{method: "PUT", pattern: ext.GetPut(), body: ext.GetBody()}
case ext.GetPatch() != "":
return &handler{method: "PATCH", pattern: ext.GetPatch(), body: ext.GetBody()}
case ext.GetDelete() != "":
return &handler{method: "DELETE", pattern: ext.GetDelete(), body: ext.GetBody()}
}
return nil
}
func (p *MicroWebModule) generate(f pgs.File) {
if len(f.Messages()) == 0 {
return
}
name := p.ctx.OutputPath(f).SetExt(".web.go")
p.AddGeneratorTemplateFile(name.String(), p.tpl, f)
}
func (p *MicroWebModule) handlerMethod(m pgs.Method) pgs.Name {
return pgs.Name(getHandler(m).method)
}
func (p *MicroWebModule) handlerPattern(m pgs.Method) pgs.Name {
return pgs.Name(getHandler(m).pattern)
}
func (p *MicroWebModule) handlerBody(m pgs.Method) pgs.Name {
return pgs.Name(getHandler(m).body)
}
func (p *MicroWebModule) handlerPrefix(m pgs.Method) pgs.Name {
return pgs.Name("")
}
func (p *MicroWebModule) marshaler(m pgs.Message) pgs.Name {
return p.ctx.Name(m) + "JSONMarshaler"
}
func (p *MicroWebModule) unmarshaler(m pgs.Message) pgs.Name {
return p.ctx.Name(m) + "JSONUnmarshaler"
}
func (p *MicroWebModule) extraImports(args ...pgs.FilePath) map[pgs.FilePath]string {
var alias string
for _, arg := range args {
if value, exists := p.pconv[arg]; exists {
arg = value
}
if _, ok := p.eimp[arg]; !ok {
parts := strings.Split(arg.String(), "/")
length := len(parts)
if length < 2 {
alias = arg.String()
} else {
alias = strings.Join(parts[length-2:], "")
}
p.eimp[arg] = alias
}
}
return p.eimp
}
func (p *MicroWebModule) getExtraImportAlias(arg pgs.FilePath) string {
if value, exists := p.pconv[arg]; exists {
arg = value
}
return p.eimp[arg]
}
const microwebTpl = `// Code generated by protoc-gen-microweb. DO NOT EDIT.
// source: {{ name .}}.proto
package {{ package . }}
{{ $imports := extraImports }}
{{ range $idx, $svc := .Services }}
{{ range .Methods }}
{{ if ne (importPath .Input) (importPath .File) }}
{{ $imports = extraImports (importPath .Input) }}
{{ end }}
{{ if ne (importPath .Output) (importPath .File) }}
{{ $imports = extraImports (importPath .Output) }}
{{ end }}
{{ end }}
{{ end }}
import (
"bytes"
"encoding/json"
{{ if gt (len .Services) 0 -}}
"net/http"
{{- end }}
"github.com/golang/protobuf/jsonpb"
{{ if gt (len .Services) 0 -}}
"github.com/go-chi/render"
"github.com/go-chi/chi/v5"
merrors "go-micro.dev/v4/errors"
{{- end }}
{{ range $key, $value := $imports }}
{{ $value }} "{{ $key }}"
{{- end }}
)
{{ range $idx, $svc := .Services }}
type web{{ $svc.Name }}Handler struct {
r chi.Router
h {{ $svc.Name }}Handler
}
func (h *web{{ $svc.Name }}Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.r.ServeHTTP(w, r)
}
{{ range .Methods }}
func (h *web{{ $svc.Name }}Handler) {{ name . }}(w http.ResponseWriter, r *http.Request) {
{{ if ne (importPath .Input) (importPath .File) -}}
req := &{{ getExtraImportAlias (importPath .Input) }}.{{ .Input.Name }}{}
{{- else -}}
req := &{{ .Input.Name }}{}
{{- end }}
{{ if ne (importPath .Output) (importPath .File) -}}
resp := &{{ getExtraImportAlias (importPath .Output) }}.{{ .Output.Name }}{}
{{- else -}}
resp := &{{ .Output.Name }}{}
{{- end }}
{{ if ne (getExtraImportAlias (importPath .Input)) "ptypesempty" -}}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusPreconditionFailed)
return
}
{{- end }}
if err := h.h.{{ name . }}(
r.Context(),
req,
resp,
); err != nil {
if merr,ok := merrors.As(err); ok && merr.Code == http.StatusNotFound {
http.Error(w, err.Error(), http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusBadRequest)
}
return
}
{{ if ne (getExtraImportAlias (importPath .Output)) "ptypesempty" -}}
{{- if eq (handlerMethod .) "POST" }}
render.Status(r, http.StatusCreated)
render.JSON(w, r, resp)
{{- end }}
{{- if eq (handlerMethod .) "DELETE" }}
render.Status(r, http.StatusOK)
render.JSON(w, r, resp)
{{- end }}
{{- if eq (handlerMethod .) "PATCH" }}
render.Status(r, http.StatusOK)
render.JSON(w, r, resp)
{{- end }}
{{- if eq (handlerMethod .) "PUT" }}
render.Status(r, http.StatusOK)
render.JSON(w, r, resp)
{{- end }}
{{- if eq (handlerMethod .) "GET" }}
render.Status(r, http.StatusOK)
render.JSON(w, r, resp)
{{- end }}
{{- else }}
render.Status(r, http.StatusNoContent)
render.NoContent(w, r)
{{- end }}
}
{{ end }}
func Register{{ .Name }}Web(r chi.Router, i {{ .Name }}Handler, middlewares ...func(http.Handler) http.Handler) {
handler := &web{{ .Name }}Handler{
r: r,
h: i,
}
{{ range .Methods }}{{ if .ServerStreaming }}{{- else -}}
r.MethodFunc("{{ handlerMethod . }}", "{{ handlerPrefix . }}{{ handlerPattern . }}", handler.{{ name .}})
{{ end }}{{- end -}}
}
{{ end }}
{{ range .AllMessages }}
// {{ marshaler . }} describes the default jsonpb.Marshaler used by all
// instances of {{ name . }}. This struct is safe to replace or modify but
// should not be done so concurrently.
var {{ marshaler . }} = new(jsonpb.Marshaler)
// MarshalJSON satisfies the encoding/json Marshaler interface. This method
// uses the more correct jsonpb package to correctly marshal the message.
func (m *{{ name . }}) MarshalJSON() ([]byte, error) {
if m == nil {
return json.Marshal(nil)
}
buf := &bytes.Buffer{}
if err := {{ marshaler . }}.Marshal(buf, m); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
var _ json.Marshaler = (*{{ name . }})(nil)
// {{ unmarshaler . }} describes the default jsonpb.Unmarshaler used by all
// instances of {{ name . }}. This struct is safe to replace or modify but
// should not be done so concurrently.
var {{ unmarshaler . }} = new(jsonpb.Unmarshaler)
// UnmarshalJSON satisfies the encoding/json Unmarshaler interface. This method
// uses the more correct jsonpb package to correctly unmarshal the message.
func (m *{{ name . }}) UnmarshalJSON(b []byte) error {
return {{ unmarshaler . }}.Unmarshal(bytes.NewReader(b), m)
}
var _ json.Unmarshaler = (*{{ name . }})(nil)
{{ end }}
`