forked from hooklift/gowsdl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gowsdl.go
650 lines (554 loc) · 14.2 KB
/
gowsdl.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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package gowsdl
import (
"bytes"
"crypto/tls"
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"text/template"
"time"
"unicode"
)
const maxRecursion uint8 = 20
// GoWSDL defines the struct for WSDL generator.
type GoWSDL struct {
loc *Location
pkg string
ignoreTLS bool
makePublicFn func(string) string
wsdl *WSDL
resolvedXSDExternals map[string]bool
currentRecursionLevel uint8
}
var cacheDir = filepath.Join(os.TempDir(), "gowsdl-cache")
func init() {
err := os.MkdirAll(cacheDir, 0700)
if err != nil {
log.Println("Create cache directory", "error", err)
os.Exit(1)
}
}
var timeout = time.Duration(30 * time.Second)
func dialTimeout(network, addr string) (net.Conn, error) {
return net.DialTimeout(network, addr, timeout)
}
func downloadFile(url string, ignoreTLS bool) ([]byte, error) {
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: ignoreTLS,
},
Dial: dialTimeout,
}
client := &http.Client{Transport: tr}
resp, err := client.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("Received response code %d", resp.StatusCode)
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return data, nil
}
// NewGoWSDL initializes WSDL generator.
func NewGoWSDL(file, pkg string, ignoreTLS bool, exportAllTypes bool) (*GoWSDL, error) {
file = strings.TrimSpace(file)
if file == "" {
return nil, errors.New("WSDL file is required to generate Go proxy")
}
pkg = strings.TrimSpace(pkg)
if pkg == "" {
pkg = "myservice"
}
makePublicFn := func(id string) string { return id }
if exportAllTypes {
makePublicFn = makePublic
}
r, err := ParseLocation(file)
if err != nil {
return nil, err
}
return &GoWSDL{
loc: r,
pkg: pkg,
ignoreTLS: ignoreTLS,
makePublicFn: makePublicFn,
}, nil
}
// Start initiaties the code generation process by starting two goroutines: one
// to generate types and another one to generate operations.
func (g *GoWSDL) Start() (map[string][]byte, error) {
gocode := make(map[string][]byte)
err := g.unmarshal()
if err != nil {
return nil, err
}
// Process WSDL nodes
for _, schema := range g.wsdl.Types.Schemas {
newTraverser(schema, g.wsdl.Types.Schemas).traverse()
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
var err error
gocode["types"], err = g.genTypes()
if err != nil {
log.Println("genTypes", "error", err)
}
}()
wg.Add(1)
go func() {
defer wg.Done()
var err error
gocode["operations"], err = g.genOperations()
if err != nil {
log.Println(err)
}
}()
wg.Wait()
gocode["header"], err = g.genHeader()
if err != nil {
log.Println(err)
}
return gocode, nil
}
func (g *GoWSDL) fetchFile(loc *Location) (data []byte, err error) {
if loc.f != "" {
log.Println("Reading", "file", loc.f)
data, err = ioutil.ReadFile(loc.f)
} else {
log.Println("Downloading", "file", loc.u.String())
data, err = downloadFile(loc.u.String(), g.ignoreTLS)
}
return
}
func (g *GoWSDL) unmarshal() error {
data, err := g.fetchFile(g.loc)
if err != nil {
return err
}
g.wsdl = new(WSDL)
err = xml.Unmarshal(data, g.wsdl)
if err != nil {
return err
}
for _, schema := range g.wsdl.Types.Schemas {
err = g.resolveXSDExternals(schema, g.loc)
if err != nil {
return err
}
}
return nil
}
func (g *GoWSDL) resolveXSDExternals(schema *XSDSchema, loc *Location) error {
download := func(base *Location, ref string) error {
location, err := base.Parse(ref)
if err != nil {
return err
}
schemaKey := location.String()
if g.resolvedXSDExternals[location.String()] {
return nil
}
if g.resolvedXSDExternals == nil {
g.resolvedXSDExternals = make(map[string]bool, maxRecursion)
}
g.resolvedXSDExternals[schemaKey] = true
var data []byte
if data, err = g.fetchFile(location); err != nil {
return err
}
newschema := new(XSDSchema)
err = xml.Unmarshal(data, newschema)
if err != nil {
return err
}
if (len(newschema.Includes) > 0 || len(newschema.Imports) > 0) &&
maxRecursion > g.currentRecursionLevel {
g.currentRecursionLevel++
err = g.resolveXSDExternals(newschema, location)
if err != nil {
return err
}
}
g.wsdl.Types.Schemas = append(g.wsdl.Types.Schemas, newschema)
return nil
}
for _, impts := range schema.Imports {
// Download the file only if we have a hint in the form of schemaLocation.
if impts.SchemaLocation == "" {
log.Printf("[WARN] Don't know where to find XSD for %s", impts.Namespace)
continue
}
if e := download(loc, impts.SchemaLocation); e != nil {
return e
}
}
for _, incl := range schema.Includes {
if e := download(loc, incl.SchemaLocation); e != nil {
return e
}
}
return nil
}
func (g *GoWSDL) genTypes() ([]byte, error) {
funcMap := template.FuncMap{
"toGoType": toGoType,
"stripns": stripns,
"replaceReservedWords": replaceReservedWords,
"replaceAttrReservedWords": replaceAttrReservedWords,
"normalize": normalize,
"makePublic": g.makePublicFn,
"makeFieldPublic": makePublic,
"comment": comment,
"removeNS": removeNS,
"goString": goString,
"findNameByType": g.findNameByType,
"removePointerFromType": removePointerFromType,
}
data := new(bytes.Buffer)
tmpl := template.Must(template.New("types").Funcs(funcMap).Parse(typesTmpl))
err := tmpl.Execute(data, g.wsdl.Types)
if err != nil {
return nil, err
}
return data.Bytes(), nil
}
func (g *GoWSDL) genOperations() ([]byte, error) {
funcMap := template.FuncMap{
"toGoType": toGoType,
"stripns": stripns,
"replaceReservedWords": replaceReservedWords,
"normalize": normalize,
"makePublic": g.makePublicFn,
"makePrivate": makePrivate,
"findType": g.findType,
"findSOAPAction": g.findSOAPAction,
"findServiceAddress": g.findServiceAddress,
}
data := new(bytes.Buffer)
tmpl := template.Must(template.New("operations").Funcs(funcMap).Parse(opsTmpl))
err := tmpl.Execute(data, g.wsdl.PortTypes)
if err != nil {
return nil, err
}
return data.Bytes(), nil
}
func (g *GoWSDL) genHeader() ([]byte, error) {
funcMap := template.FuncMap{
"toGoType": toGoType,
"stripns": stripns,
"replaceReservedWords": replaceReservedWords,
"normalize": normalize,
"makePublic": g.makePublicFn,
"findType": g.findType,
"comment": comment,
}
data := new(bytes.Buffer)
tmpl := template.Must(template.New("header").Funcs(funcMap).Parse(headerTmpl))
err := tmpl.Execute(data, g.pkg)
if err != nil {
return nil, err
}
return data.Bytes(), nil
}
var reservedWords = map[string]string{
"break": "break_",
"default": "default_",
"func": "func_",
"interface": "interface_",
"select": "select_",
"case": "case_",
"defer": "defer_",
"go": "go_",
"map": "map_",
"struct": "struct_",
"chan": "chan_",
"else": "else_",
"goto": "goto_",
"package": "package_",
"switch": "switch_",
"const": "const_",
"fallthrough": "fallthrough_",
"if": "if_",
"range": "range_",
"type": "type_",
"continue": "continue_",
"for": "for_",
"import": "import_",
"return": "return_",
"var": "var_",
}
var reservedWordsInAttr = map[string]string{
"break": "break_",
"default": "default_",
"func": "func_",
"interface": "interface_",
"select": "select_",
"case": "case_",
"defer": "defer_",
"go": "go_",
"map": "map_",
"struct": "struct_",
"chan": "chan_",
"else": "else_",
"goto": "goto_",
"package": "package_",
"switch": "switch_",
"const": "const_",
"fallthrough": "fallthrough_",
"if": "if_",
"range": "range_",
"type": "type_",
"continue": "continue_",
"for": "for_",
"import": "import_",
"return": "return_",
"var": "var_",
"string": "astring",
}
// Replaces Go reserved keywords to avoid compilation issues
func replaceReservedWords(identifier string) string {
value := reservedWords[identifier]
if value != "" {
return value
}
return normalize(identifier)
}
// Replaces Go reserved keywords to avoid compilation issues
func replaceAttrReservedWords(identifier string) string {
value := reservedWordsInAttr[identifier]
if value != "" {
return value
}
return normalize(identifier)
}
// Normalizes value to be used as a valid Go identifier, avoiding compilation issues
func normalize(value string) string {
mapping := func(r rune) rune {
if r == '.' {
return '_'
}
if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
return r
}
return -1
}
return strings.Map(mapping, value)
}
func goString(s string) string {
return strings.Replace(s, "\"", "\\\"", -1)
}
var xsd2GoTypes = map[string]string{
"string": "string",
"token": "string",
"float": "float32",
"double": "float64",
"decimal": "float64",
"integer": "int32",
"int": "int32",
"short": "int16",
"byte": "int8",
"long": "int64",
"boolean": "bool",
"datetime": "time.Time",
"date": "time.Time",
"time": "time.Time",
"base64binary": "[]byte",
"hexbinary": "[]byte",
"unsignedint": "uint32",
"unsignedshort": "uint16",
"unsignedbyte": "byte",
"unsignedlong": "uint64",
"anytype": "AnyType",
"ncname": "NCName",
"anyuri": "AnyURI",
}
func removeNS(xsdType string) string {
// Handles name space, ie. xsd:string, xs:string
r := strings.Split(xsdType, ":")
if len(r) == 2 {
return r[1]
}
return r[0]
}
func toGoType(xsdType string) string {
// Handles name space, ie. xsd:string, xs:string
r := strings.Split(xsdType, ":")
t := r[0]
if len(r) == 2 {
t = r[1]
}
value := xsd2GoTypes[strings.ToLower(t)]
if value != "" {
return value
}
return "*" + replaceReservedWords(makePublic(t))
}
func removePointerFromType(goType string) string {
return regexp.MustCompile("^\\s*\\*").ReplaceAllLiteralString(goType, "")
}
// Given a message, finds its type.
//
// I'm not very proud of this function but
// it works for now and performance doesn't
// seem critical at this point
func (g *GoWSDL) findType(message string) string {
message = stripns(message)
for _, msg := range g.wsdl.Messages {
if msg.Name != message {
continue
}
// Assumes document/literal wrapped WS-I
if len(msg.Parts) == 0 {
// Message does not have parts. This could be a Port
// with HTTP binding or SOAP 1.2 binding, which are not currently
// supported.
log.Printf("[WARN] %s message doesn't have any parts, ignoring message...", msg.Name)
continue
}
part := msg.Parts[0]
if part.Type != "" {
return stripns(part.Type)
}
elRef := stripns(part.Element)
for _, schema := range g.wsdl.Types.Schemas {
for _, el := range schema.Elements {
if strings.EqualFold(elRef, el.Name) {
if el.Type != "" {
return stripns(el.Type)
}
return el.Name
}
}
}
}
return ""
}
// Given a type, check if there's SimpleType with that type, and return its name.
func (g *GoWSDL) findNameByType(name string) string {
name = stripns(name)
for _, schema := range g.wsdl.Types.Schemas {
for _, elem := range schema.Elements {
if stripns(elem.Type) == name {
return elem.Name
}
}
}
return name
}
// TODO(c4milo): Add support for namespaces instead of striping them out
// TODO(c4milo): improve runtime complexity if performance turns out to be an issue.
func (g *GoWSDL) findSOAPAction(operation, portType string) string {
for _, binding := range g.wsdl.Binding {
if strings.ToUpper(stripns(binding.Type)) != strings.ToUpper(portType) {
continue
}
for _, soapOp := range binding.Operations {
if soapOp.Name == operation {
return soapOp.SOAPOperation.SOAPAction
}
}
}
return ""
}
func (g *GoWSDL) findServiceAddress(name string) string {
for _, service := range g.wsdl.Service {
for _, port := range service.Ports {
if port.Name == name {
return port.SOAPAddress.Location
}
}
}
return ""
}
// TODO(c4milo): Add namespace support instead of stripping it
func stripns(xsdType string) string {
r := strings.Split(xsdType, ":")
t := r[0]
if len(r) == 2 {
t = r[1]
}
return t
}
func makePublic(identifier string) string {
if isBasicType(identifier) {
return identifier
}
field := []rune(identifier)
if len(field) == 0 {
return identifier
}
field[0] = unicode.ToUpper(field[0])
return string(field)
}
var basicTypes = map[string]string{
"string": "string",
"float32": "float32",
"float64": "float64",
"int": "int",
"int8": "int8",
"int16": "int16",
"int32": "int32",
"int64": "int64",
"bool": "bool",
"time.Time": "time.Time",
"[]byte": "[]byte",
"byte": "byte",
"uint16": "uint16",
"uint32": "uint32",
"uinit64": "uint64",
"interface{}": "interface{}",
}
func isBasicType(identifier string) bool {
if _, exists := basicTypes[identifier]; exists {
return true
}
return false
}
func makePrivate(identifier string) string {
field := []rune(identifier)
if len(field) == 0 {
return identifier
}
field[0] = unicode.ToLower(field[0])
return string(field)
}
func comment(text string) string {
lines := strings.Split(text, "\n")
var output string
if len(lines) == 1 && lines[0] == "" {
return ""
}
// Helps to determine if there is an actual comment without screwing newlines
// in real comments.
hasComment := false
for _, line := range lines {
line = strings.TrimLeftFunc(line, unicode.IsSpace)
if line != "" {
hasComment = true
}
output += "\n// " + line
}
if hasComment {
return output
}
return ""
}