forked from hooklift/gowsdl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsoap.go
386 lines (319 loc) · 9.45 KB
/
soap.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
package soap
import (
"bytes"
"context"
"crypto/tls"
"encoding/xml"
"fmt"
"net"
"net/http"
"time"
)
type SOAPEncoder interface {
Encode(v interface{}) error
Flush() error
}
type SOAPDecoder interface {
Decode(v interface{}) error
}
type SOAPEnvelope struct {
XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"`
Header *SOAPHeader
Body SOAPBody
}
type SOAPHeader struct {
XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Header"`
Headers []interface{}
}
type SOAPBody struct {
XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"`
Fault *SOAPFault `xml:",omitempty"`
Content interface{} `xml:",omitempty"`
}
// UnmarshalXML unmarshals SOAPBody xml
func (b *SOAPBody) UnmarshalXML(d *xml.Decoder, _ xml.StartElement) error {
if b.Content == nil {
return xml.UnmarshalError("Content must be a pointer to a struct")
}
var (
token xml.Token
err error
consumed bool
)
Loop:
for {
if token, err = d.Token(); err != nil {
return err
}
if token == nil {
break
}
switch se := token.(type) {
case xml.StartElement:
if consumed {
return xml.UnmarshalError("Found multiple elements inside SOAP body; not wrapped-document/literal WS-I compliant")
} else if se.Name.Space == "http://schemas.xmlsoap.org/soap/envelope/" && se.Name.Local == "Fault" {
b.Fault = &SOAPFault{}
b.Content = nil
err = d.DecodeElement(b.Fault, &se)
if err != nil {
return err
}
consumed = true
} else {
if err = d.DecodeElement(b.Content, &se); err != nil {
return err
}
consumed = true
}
case xml.EndElement:
break Loop
}
}
return nil
}
type SOAPFault struct {
XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault"`
Code string `xml:"faultcode,omitempty"`
String string `xml:"faultstring,omitempty"`
Actor string `xml:"faultactor,omitempty"`
Detail string `xml:"detail,omitempty"`
}
func (f *SOAPFault) Error() string {
return f.String
}
const (
// Predefined WSS namespaces to be used in
WssNsWSSE string = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
WssNsWSU string = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
WssNsType string = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"
mtomContentType string = `multipart/related; start-info="application/soap+xml"; type="application/xop+xml"; boundary="%s"`
)
type WSSSecurityHeader struct {
XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ wsse:Security"`
XmlNSWsse string `xml:"xmlns:wsse,attr"`
MustUnderstand string `xml:"mustUnderstand,attr,omitempty"`
Token *WSSUsernameToken `xml:",omitempty"`
}
type WSSUsernameToken struct {
XMLName xml.Name `xml:"wsse:UsernameToken"`
XmlNSWsu string `xml:"xmlns:wsu,attr"`
XmlNSWsse string `xml:"xmlns:wsse,attr"`
Id string `xml:"wsu:Id,attr,omitempty"`
Username *WSSUsername `xml:",omitempty"`
Password *WSSPassword `xml:",omitempty"`
}
type WSSUsername struct {
XMLName xml.Name `xml:"wsse:Username"`
XmlNSWsse string `xml:"xmlns:wsse,attr"`
Data string `xml:",chardata"`
}
type WSSPassword struct {
XMLName xml.Name `xml:"wsse:Password"`
XmlNSWsse string `xml:"xmlns:wsse,attr"`
XmlNSType string `xml:"Type,attr"`
Data string `xml:",chardata"`
}
// NewWSSSecurityHeader creates WSSSecurityHeader instance
func NewWSSSecurityHeader(user, pass, tokenID, mustUnderstand string) *WSSSecurityHeader {
hdr := &WSSSecurityHeader{XmlNSWsse: WssNsWSSE, MustUnderstand: mustUnderstand}
hdr.Token = &WSSUsernameToken{XmlNSWsu: WssNsWSU, XmlNSWsse: WssNsWSSE, Id: tokenID}
hdr.Token.Username = &WSSUsername{XmlNSWsse: WssNsWSSE, Data: user}
hdr.Token.Password = &WSSPassword{XmlNSWsse: WssNsWSSE, XmlNSType: WssNsType, Data: pass}
return hdr
}
type basicAuth struct {
Login string
Password string
}
type options struct {
tlsCfg *tls.Config
auth *basicAuth
timeout time.Duration
contimeout time.Duration
tlshshaketimeout time.Duration
client HTTPClient
httpHeaders map[string]string
mtom bool
}
var defaultOptions = options{
timeout: time.Duration(30 * time.Second),
contimeout: time.Duration(90 * time.Second),
tlshshaketimeout: time.Duration(15 * time.Second),
}
// A Option sets options such as credentials, tls, etc.
type Option func(*options)
// WithHTTPClient is an Option to set the HTTP client to use
// This cannot be used with WithTLSHandshakeTimeout, WithTLS,
// WithTimeout options
func WithHTTPClient(c HTTPClient) Option {
return func(o *options) {
o.client = c
}
}
// WithTLSHandshakeTimeout is an Option to set default tls handshake timeout
// This option cannot be used with WithHTTPClient
func WithTLSHandshakeTimeout(t time.Duration) Option {
return func(o *options) {
o.tlshshaketimeout = t
}
}
// WithRequestTimeout is an Option to set default end-end connection timeout
// This option cannot be used with WithHTTPClient
func WithRequestTimeout(t time.Duration) Option {
return func(o *options) {
o.contimeout = t
}
}
// WithBasicAuth is an Option to set BasicAuth
func WithBasicAuth(login, password string) Option {
return func(o *options) {
o.auth = &basicAuth{Login: login, Password: password}
}
}
// WithTLS is an Option to set tls config
// This option cannot be used with WithHTTPClient
func WithTLS(tls *tls.Config) Option {
return func(o *options) {
o.tlsCfg = tls
}
}
// WithTimeout is an Option to set default HTTP dial timeout
func WithTimeout(t time.Duration) Option {
return func(o *options) {
o.timeout = t
}
}
// WithHTTPHeaders is an Option to set global HTTP headers for all requests
func WithHTTPHeaders(headers map[string]string) Option {
return func(o *options) {
o.httpHeaders = headers
}
}
// WithMTOM is an Option to set Message Transmission Optimization Mechanism
// MTOM encodes fields of type Binary using XOP.
func WithMTOM() Option {
return func(o *options) {
o.mtom = true
}
}
// Client is soap client
type Client struct {
url string
opts *options
headers []interface{}
}
// HTTPClient is a client which can make HTTP requests
// An example implementation is net/http.Client
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
// NewClient creates new SOAP client instance
func NewClient(url string, opt ...Option) *Client {
opts := defaultOptions
for _, o := range opt {
o(&opts)
}
return &Client{
url: url,
opts: &opts,
}
}
// AddHeader adds envelope header
// For correct behavior, every header must contain a `XMLName` field. Refer to #121 for details
func (s *Client) AddHeader(header interface{}) {
s.headers = append(s.headers, header)
}
// SetHeaders sets envelope headers, overwriting any existing headers.
// For correct behavior, every header must contain a `XMLName` field. Refer to #121 for details
func (s *Client) SetHeaders(headers ...interface{}) {
s.headers = headers
}
// CallContext performs HTTP POST request with a context
func (s *Client) CallContext(ctx context.Context, soapAction string, request, response interface{}) error {
return s.call(ctx, soapAction, request, response)
}
// Call performs HTTP POST request
func (s *Client) Call(soapAction string, request, response interface{}) error {
return s.call(context.Background(), soapAction, request, response)
}
func (s *Client) call(ctx context.Context, soapAction string, request, response interface{}) error {
envelope := SOAPEnvelope{}
if s.headers != nil && len(s.headers) > 0 {
envelope.Header = &SOAPHeader{
Headers: s.headers,
}
}
envelope.Body.Content = request
buffer := new(bytes.Buffer)
var encoder SOAPEncoder
if s.opts.mtom {
encoder = newMtomEncoder(buffer)
} else {
encoder = xml.NewEncoder(buffer)
}
if err := encoder.Encode(envelope); err != nil {
return err
}
if err := encoder.Flush(); err != nil {
return err
}
req, err := http.NewRequest("POST", s.url, buffer)
if err != nil {
return err
}
if s.opts.auth != nil {
req.SetBasicAuth(s.opts.auth.Login, s.opts.auth.Password)
}
req = req.WithContext(ctx)
if s.opts.mtom {
req.Header.Add("Content-Type", fmt.Sprintf(mtomContentType, encoder.(*mtomEncoder).Boundary()))
} else {
req.Header.Add("Content-Type", "text/xml; charset=\"utf-8\"")
}
req.Header.Add("SOAPAction", soapAction)
req.Header.Set("User-Agent", "gowsdl/0.1")
if s.opts.httpHeaders != nil {
for k, v := range s.opts.httpHeaders {
req.Header.Set(k, v)
}
}
req.Close = true
client := s.opts.client
if client == nil {
tr := &http.Transport{
TLSClientConfig: s.opts.tlsCfg,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
d := net.Dialer{Timeout: s.opts.timeout}
return d.DialContext(ctx, network, addr)
},
TLSHandshakeTimeout: s.opts.tlshshaketimeout,
}
client = &http.Client{Timeout: s.opts.contimeout, Transport: tr}
}
res, err := client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
respEnvelope := new(SOAPEnvelope)
respEnvelope.Body = SOAPBody{Content: response}
mtomBoundary, err := getMtomHeader(res.Header.Get("Content-Type"))
if err != nil {
return err
}
var dec SOAPDecoder
if mtomBoundary != "" {
dec = newMtomDecoder(res.Body, mtomBoundary)
} else {
dec = xml.NewDecoder(res.Body)
}
if err := dec.Decode(respEnvelope); err != nil {
return err
}
fault := respEnvelope.Body.Fault
if fault != nil {
return fault
}
return nil
}