forked from hooklift/gowsdl
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gowsdl.go
341 lines (283 loc) · 7.16 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
// 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"
"strings"
"sync"
"text/template"
"time"
)
const maxRecursion uint8 = 100
// GoWSDL defines the struct for WSDL generator.
type GoWSDL struct {
loc *Location
pkg string
ignoreTLS bool
ignoreTypeNs bool
auth *basicAuth
exportAllTypes bool
wsdl *WSDL
resolvedXSDExternals map[string]bool
currentRecursionLevel uint8
tmplFuncs *tmplFunctions
}
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, auth *basicAuth) ([]byte, error) {
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: ignoreTLS,
},
Dial: dialTimeout,
}
client := &http.Client{Transport: tr}
req, _ := http.NewRequest("GET", url, nil)
if auth != nil {
req.SetBasicAuth(auth.Login, auth.Password)
}
resp, err := client.Do(req)
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"
}
r, err := ParseLocation(file)
if err != nil {
return nil, err
}
return &GoWSDL{
loc: r,
pkg: pkg,
ignoreTLS: ignoreTLS,
exportAllTypes: exportAllTypes,
}, nil
}
func (g *GoWSDL) SetBasicAuth(login, password string) {
g.auth = &basicAuth{Login: login, Password: password}
}
func (g *GoWSDL) SetIgnoreTypeNamespaces(ignore bool) {
g.ignoreTypeNs = ignore
}
// Start initiates 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
}
g.refineRawWsdlData()
// Process WSDL nodes
for _, schema := range g.wsdl.Types.Schemas {
newTraverser(schema, g.wsdl.Types.Schemas).traverse()
}
g.tmplFuncs = createTmplFunctions(g)
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)
}
gocode["soap"], err = g.genSOAPClient()
if err != nil {
log.Println(err)
}
return gocode, nil
}
func (g *GoWSDL) fetchFile(loc *Location) (data []byte, err error) {
if loc.f != "" {
log.Println("[INFO] Reading", "file", loc.f)
data, err = ioutil.ReadFile(loc.f)
} else {
log.Println("[INFO] Downloading", "file", loc.u.String())
data, err = downloadFile(loc.u.String(), g.ignoreTLS, g.auth)
}
return
}
func (g *GoWSDL) unmarshal() error {
data, err := g.fetchFile(g.loc)
if err != nil {
return err
}
g.wsdl = new(WSDL)
if err = xml.Unmarshal(data, g.wsdl); err != nil {
return err
}
g.resolvedXSDExternals = make(map[string]bool, maxRecursion)
for _, schema := range g.wsdl.Types.Schemas {
if err = g.resolveXSDExternals(schema, g.loc); err != nil {
return err
}
}
return nil
}
func (g *GoWSDL) resolveXSDExternals(schema *XSDSchema, loc *Location) error {
if schema == nil || loc == nil {
return nil
}
g.currentRecursionLevel++
if g.currentRecursionLevel > maxRecursion {
return nil
}
currentSchemaKey := loc.String()
if g.resolvedXSDExternals[currentSchemaKey] {
return nil
}
g.resolvedXSDExternals[currentSchemaKey] = true
log.Printf("[INFO] Resolving external XSDs for Schema %s", currentSchemaKey)
handleExternalSchema := func(base *Location, schemaLoc string) error {
var (
newSchema *XSDSchema
newSchemaLoc *Location
err error
)
if newSchema, newSchemaLoc, err = g.downloadSchemaIfRequired(loc, schemaLoc); err == nil && newSchema != nil {
g.wsdl.Types.Schemas = append(g.wsdl.Types.Schemas, newSchema)
err = g.resolveXSDExternals(newSchema, newSchemaLoc)
}
return err
}
var err error
for _, impt := range schema.Imports {
if err != nil {
break
}
if impt.SchemaLocation == "" {
log.Printf("[WARN] Don't know where to find XSD for %s", impt.Namespace)
continue
}
err = handleExternalSchema(loc, impt.SchemaLocation)
}
for _, incl := range schema.Includes {
if err != nil {
break
}
if incl.SchemaLocation == "" {
continue
}
err = handleExternalSchema(loc, incl.SchemaLocation)
}
return err
}
func (g *GoWSDL) downloadSchemaIfRequired(base *Location,
locationRef string) (newSchema *XSDSchema,
newSchemaLoc *Location,
err error) {
if newSchemaLoc, err = base.Parse(locationRef); err != nil {
return
}
schemaKey := newSchemaLoc.String()
if g.resolvedXSDExternals[schemaKey] {
return
}
var data []byte
if data, err = g.fetchFile(newSchemaLoc); err != nil {
return
}
newSchema = new(XSDSchema)
if err = xml.Unmarshal(data, newSchema); err != nil {
return
}
log.Printf("[INFO] Downloaded Schema %s", newSchema.TargetNamespace)
return
}
func (g *GoWSDL) refineRawWsdlData() {
g.wsdl.refine(g.ignoreTypeNs)
}
func (g *GoWSDL) genTypes() ([]byte, error) {
data := new(bytes.Buffer)
tmpl := template.Must(template.New("types").
Funcs(g.tmplFuncs.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) {
data := new(bytes.Buffer)
tmpl := template.Must(template.New("operations").
Funcs(g.tmplFuncs.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) {
data := new(bytes.Buffer)
tmpl := template.Must(template.New("header").
Funcs(g.tmplFuncs.funcMap).Parse(headerTmpl))
err := tmpl.Execute(data, g.pkg)
if err != nil {
return nil, err
}
return data.Bytes(), nil
}
func (g *GoWSDL) genSOAPClient() ([]byte, error) {
data := new(bytes.Buffer)
tmpl := template.Must(template.New("soapclient").Parse(soapTmpl))
err := tmpl.Execute(data, g.pkg)
if err != nil {
return nil, err
}
return data.Bytes(), nil
}