-
Notifications
You must be signed in to change notification settings - Fork 115
/
wsdlgen.go
351 lines (319 loc) · 9.15 KB
/
wsdlgen.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// Package wsdlgen generates Go source code from wsdl documents.
//
// The wsdlgen package generates Go source for calling the various
// methods defined in a WSDL (Web Service Definition Language) document.
// The generated Go source is self-contained, with no dependencies on
// non-standard packages.
//
// Code generation for the wsdlgen package can be configured by using
// the provided Option functions.
package wsdlgen // import "aqwari.net/xml/wsdlgen"
import (
"encoding/xml"
"errors"
"fmt"
"go/ast"
"io/ioutil"
"strings"
"aqwari.net/xml/internal/gen"
"aqwari.net/xml/wsdl"
"aqwari.net/xml/xsd"
"aqwari.net/xml/xsdgen"
)
// Types conforming to the Logger interface can receive information about
// the code generation process.
type Logger interface {
Printf(format string, v ...interface{})
}
type printer struct {
*Config
code *xsdgen.Code
wsdl *wsdl.Definition
file *ast.File
}
// Provides aspects about an RPC call to the template for the function
// bodies.
type opArgs struct {
// formatted with appropriate variable names
input, output []string
// URL to send request to
Address string
// POST or GET
Method string
SOAPAction string
// Name of the method to call
MsgName xml.Name
// if we're returning individual values, these slices
// are in an order matching the input/output slices.
InputName, OutputName xml.Name
InputFields []field
OutputFields []field
// If not "", inputs come in a wrapper struct
InputType string
// If not "", we return values in a wrapper struct
ReturnType string
ReturnFields []field
}
// struct members. Need to export the fields for our template
type field struct {
Name, Type string
XMLName xml.Name
// If this is a wrapper struct for >InputThreshold arguments,
// PublicType holds the type that we want to expose to the
// user. For example, if the web service expects an xsdDate
// to be sent to it, PublicType will be time.Time and a conversion
// will take place before sending the request to the server.
PublicType string
// This refers to the name of the value to assign to this field
// in the argument list. Empty for return values.
InputArg string
}
// GenAST creates a Go source file containing type and method declarations
// that can be used to access the service described in the provided set of wsdl
// files.
func (cfg *Config) GenAST(files ...string) (*ast.File, error) {
if len(files) == 0 {
return nil, errors.New("must provide at least one file name")
}
if cfg.pkgName == "" {
cfg.pkgName = "ws"
}
if cfg.pkgHeader == "" {
cfg.pkgHeader = fmt.Sprintf("Package %s", cfg.pkgName)
}
docs := make([][]byte, 0, len(files))
for _, filename := range files {
if data, err := ioutil.ReadFile(filename); err != nil {
return nil, err
} else {
cfg.debugf("read %s", filename)
docs = append(docs, data)
}
}
cfg.debugf("parsing WSDL file %s", files[0])
def, err := wsdl.Parse(docs[0])
if err != nil {
return nil, err
}
cfg.verbosef("generating type declarations from xml schema")
code, err := cfg.xsdgen.GenCode(docs...)
if err != nil {
return nil, err
}
cfg.verbosef("generating function definitions from WSDL")
return cfg.genAST(def, code)
}
func (cfg *Config) genAST(def *wsdl.Definition, code *xsdgen.Code) (*ast.File, error) {
file, err := code.GenAST()
if err != nil {
return nil, err
}
file.Name = ast.NewIdent(cfg.pkgName)
file = gen.PackageDoc(file, cfg.pkgHeader, "\n", def.Doc)
p := &printer{
Config: cfg,
wsdl: def,
file: file,
code: code,
}
return p.genAST()
}
func (p *printer) genAST() (*ast.File, error) {
p.addHelpers()
for _, port := range p.wsdl.Ports {
if err := p.port(port); err != nil {
return nil, err
}
}
return p.file, nil
}
func (p *printer) port(port wsdl.Port) error {
for _, operation := range port.Operations {
if err := p.operation(port, operation); err != nil {
return err
}
}
return nil
}
func (p *printer) operation(port wsdl.Port, op wsdl.Operation) error {
input, ok := p.wsdl.Message[op.Input]
if !ok {
return fmt.Errorf("unknown input message type %s", op.Input.Local)
}
output, ok := p.wsdl.Message[op.Output]
if !ok {
return fmt.Errorf("unknown output message type %s", op.Output.Local)
}
params, err := p.opArgs(port.Address, port.Method, op, input, output)
if err != nil {
return err
}
if params.InputType != "" {
decls, err := gen.Snippets(params, `
type {{.InputType}} struct {
{{ range .InputFields -}}
{{.Name}} {{.PublicType}}
{{ end -}}
}`,
)
if err != nil {
return err
}
p.file.Decls = append(p.file.Decls, decls...)
}
if params.ReturnType != "" {
decls, err := gen.Snippets(params, `
type {{.ReturnType}} struct {
{{ range .ReturnFields -}}
{{.Name}} {{.Type}}
{{ end -}}
}`,
)
if err != nil {
return err
}
p.file.Decls = append(p.file.Decls, decls...)
}
args := append([]string{"ctx context.Context"}, params.input...)
fn := gen.Func(p.xsdgen.NameOf(op.Name)).
Comment(op.Doc).
Receiver("c *Client").
Args(args...).
BodyTmpl(`
var input struct {
XMLName struct{} `+"`"+`xml:"{{.MsgName.Space}} {{.MsgName.Local}}"`+"`"+`
Args struct {
{{ range .InputFields -}}
{{.Name}} {{.Type}} `+"`"+`xml:"{{.XMLName.Space}} {{.XMLName.Local}}"`+"`"+`
{{ end -}}
}`+"`xml:\"{{.InputName.Space}} {{.InputName.Local}}\"`"+`
}
{{- range .InputFields }}
input.Args.{{.Name}} = {{.Type}}({{.InputArg}})
{{ end }}
var output struct {
XMLName struct{} `+"`"+`xml:"{{.MsgName.Space}} {{.MsgName.Local}}"`+"`"+`
Args struct {
{{ range .OutputFields -}}
{{.Name}} {{.Type}} `+"`"+`xml:"{{.XMLName.Space}} {{.XMLName.Local}}"`+"`"+`
{{ end -}}
}`+"`xml:\"{{.OutputName.Space}} {{.OutputName.Local}}\"`"+`
}
err := c.do(ctx, {{.Method|printf "%q"}}, {{.Address|printf "%q"}}, {{.SOAPAction|printf "%q"}}, &input, &output)
{{ if .OutputFields -}}
return {{ range .OutputFields }}{{.Type}}(output.Args.{{.Name}}), {{ end }} err
{{- else if .ReturnType -}}
var result {{ .ReturnType }}
{{ range .ReturnFields -}}
result.{{.Name}} = {{.Type}}(output.Args.{{.InputArg}})
{{ end -}}
return result, err
{{- else -}}
return err
{{- end -}}
`, params).
Returns(params.output...)
if decl, err := fn.Decl(); err != nil {
return err
} else {
p.file.Decls = append(p.file.Decls, decl)
}
return nil
}
// The xsdgen package generates private types for some builtin
// types. These types should be hidden from the user and converted
// on the fly.
func exposeType(typ string) string {
switch typ {
case "xsdDate", "xsdTime", "xsdDateTime", "gDay",
"gMonth", "gMonthDay", "gYear", "gYearMonth":
return "time.Time"
case "hexBinary", "base64Binary":
return "[]byte"
case "idrefs", "nmtokens", "notation", "entities":
return "[]string"
}
return typ
}
func (p *printer) getPartType(part wsdl.Part) (string, error) {
if part.Type.Local != "" {
return p.code.NameOf(part.Type), nil
}
if part.Element.Local != "" {
doc, ok := p.code.DocType(part.Element.Space)
if !ok {
return "", fmt.Errorf("part %s: could not lookup element %v",
part.Name, part.Element)
}
for _, el := range doc.Elements {
if el.Name == part.Element {
return p.code.NameOf(xsd.XMLName(el.Type)), nil
}
}
}
return "", fmt.Errorf("part %s has no element or type", part.Name)
}
func (p *printer) opArgs(addr, method string, op wsdl.Operation, input, output wsdl.Message) (opArgs, error) {
var args opArgs
args.Address = addr
args.Method = method
args.SOAPAction = op.SOAPAction
args.MsgName = op.Name
args.InputName = input.Name
for _, part := range input.Parts {
typ, err := p.getPartType(part)
if err != nil {
return args, err
}
inputType := exposeType(typ)
vname := gen.Sanitize(part.Name)
if vname == typ {
vname += "_"
}
args.input = append(args.input, vname+" "+inputType)
args.InputFields = append(args.InputFields, field{
Name: strings.Title(part.Name),
Type: typ,
PublicType: exposeType(typ),
XMLName: xml.Name{p.wsdl.TargetNS, part.Name},
InputArg: vname,
})
}
if len(args.input) > p.maxArgs {
args.InputType = strings.Title(args.InputName.Local)
args.input = []string{"v " + args.InputName.Local}
for i, v := range input.Parts {
args.InputFields[i].InputArg = "v." + strings.Title(v.Name)
}
}
args.OutputName = output.Name
for _, part := range output.Parts {
typ, err := p.getPartType(part)
if err != nil {
return args, err
}
outputType := exposeType(typ)
args.output = append(args.output, outputType)
args.OutputFields = append(args.OutputFields, field{
Name: strings.Title(part.Name),
Type: typ,
XMLName: xml.Name{p.wsdl.TargetNS, part.Name},
})
}
if len(args.output) > p.maxReturns {
args.ReturnType = strings.Title(args.OutputName.Local)
args.ReturnFields = make([]field, len(args.OutputFields))
for i, v := range args.OutputFields {
args.ReturnFields[i] = field{
Name: v.Name,
Type: exposeType(v.Type),
InputArg: v.Name,
}
}
args.output = []string{args.ReturnType}
}
// NOTE(droyo) if we decide to name our return values,
// we have to change this too.
args.output = append(args.output, "error")
return args, nil
}