-
-
Notifications
You must be signed in to change notification settings - Fork 178
/
soap.go
315 lines (262 loc) · 7.2 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
package gosoap
import (
"bytes"
"encoding/xml"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"sync"
"time"
"golang.org/x/net/html/charset"
)
type SoapParams interface{}
// HeaderParams holds params specific to the header
type HeaderParams map[string]interface{}
// Params type is used to set the params in soap request
type Params map[string]interface{}
type ArrayParams [][2]interface{}
type SliceParams []interface{}
type DumpLogger interface {
LogRequest(method string, dump []byte)
LogResponse(method string, dump []byte)
}
type fmtLogger struct{}
func (l *fmtLogger) LogRequest(method string, dump []byte) {
fmt.Printf("Request:\n%v\n----\n", string(dump))
}
func (l *fmtLogger) LogResponse(method string, dump []byte) {
fmt.Printf("Response:\n%v\n----\n", string(dump))
}
// Config config the Client
type Config struct {
Dump bool
Logger DumpLogger
}
// SoapClient return new *Client to handle the requests with the WSDL
func SoapClient(wsdl string, httpClient *http.Client) (*Client, error) {
return SoapClientWithConfig(wsdl, httpClient, &Config{Dump: false, Logger: &fmtLogger{}})
}
// SoapClientWithConfig return new *Client to handle the requests with the WSDL
func SoapClientWithConfig(wsdl string, httpClient *http.Client, config *Config) (*Client, error) {
_, err := url.Parse(wsdl)
if err != nil {
return nil, err
}
if httpClient == nil {
httpClient = &http.Client{}
}
if config.Logger == nil {
config.Logger = &fmtLogger{}
}
c := &Client{
wsdl: wsdl,
config: config,
HTTPClient: httpClient,
AutoAction: false,
}
return c, nil
}
// Client struct hold all the information about WSDL,
// request and response of the server
type Client struct {
HTTPClient *http.Client
AutoAction bool
URL string
HeaderName string
HeaderParams SoapParams
Definitions *wsdlDefinitions
// Must be set before first request otherwise has no effect, minimum is 15 minutes.
RefreshDefinitionsAfter time.Duration
Username string
Password string
once sync.Once
definitionsErr error
onRequest sync.WaitGroup
onDefinitionsRefresh sync.WaitGroup
wsdl string
config *Config
}
// Call call's the method m with Params p
func (c *Client) Call(m string, p SoapParams) (res *Response, err error) {
return c.Do(NewRequest(m, p))
}
// CallByStruct call's by struct
func (c *Client) CallByStruct(s RequestStruct) (res *Response, err error) {
req, err := NewRequestByStruct(s)
if err != nil {
return nil, err
}
return c.Do(req)
}
func (c *Client) waitAndRefreshDefinitions(d time.Duration) {
for {
time.Sleep(d)
c.onRequest.Wait()
c.onDefinitionsRefresh.Add(1)
c.initWsdl()
c.onDefinitionsRefresh.Done()
}
}
func (c *Client) initWsdl() {
c.Definitions, c.definitionsErr = getWsdlDefinitions(c.wsdl, c.HTTPClient)
if c.definitionsErr == nil {
c.URL = strings.TrimSuffix(c.Definitions.TargetNamespace, "/")
}
}
// SetWSDL set WSDL url
func (c *Client) SetWSDL(wsdl string) {
c.onRequest.Wait()
c.onDefinitionsRefresh.Wait()
c.onRequest.Add(1)
c.onDefinitionsRefresh.Add(1)
defer c.onRequest.Done()
defer c.onDefinitionsRefresh.Done()
c.wsdl = wsdl
c.initWsdl()
}
// Do Process Soap Request
func (c *Client) Do(req *Request) (res *Response, err error) {
c.onDefinitionsRefresh.Wait()
c.onRequest.Add(1)
defer c.onRequest.Done()
c.once.Do(func() {
c.initWsdl()
// 15 minute to prevent abuse.
if c.RefreshDefinitionsAfter >= 15*time.Minute {
go c.waitAndRefreshDefinitions(c.RefreshDefinitionsAfter)
}
})
if c.definitionsErr != nil {
return nil, c.definitionsErr
}
if c.Definitions == nil {
return nil, errors.New("wsdl definitions not found")
}
if c.Definitions.Services == nil {
return nil, errors.New("No Services found in wsdl definitions")
}
p := &process{
Client: c,
Request: req,
SoapAction: c.Definitions.GetSoapActionFromWsdlOperation(req.Method),
}
if p.SoapAction == "" && c.AutoAction {
p.SoapAction = fmt.Sprintf("%s/%s/%s", c.URL, c.Definitions.Services[0].Name, req.Method)
}
p.Payload, err = xml.MarshalIndent(p, "", " ")
if err != nil {
return nil, err
}
b, err := p.doRequest(c.Definitions.Services[0].Ports[0].SoapAddresses[0].Location)
if err != nil {
return nil, ErrorWithPayload{err, p.Payload}
}
var soap SoapEnvelope
// err = xml.Unmarshal(b, &soap)
// error: xml: encoding "ISO-8859-1" declared but Decoder.CharsetReader is nil
// https://stackoverflow.com/questions/6002619/unmarshal-an-iso-8859-1-xml-input-in-go
// https://github.com/golang/go/issues/8937
decoder := xml.NewDecoder(bytes.NewReader(b))
decoder.CharsetReader = charset.NewReaderLabel
err = decoder.Decode(&soap)
res = &Response{
Body: soap.Body.Contents,
Header: soap.Header.Contents,
Payload: p.Payload,
}
if err != nil {
return res, ErrorWithPayload{err, p.Payload}
}
return res, nil
}
type process struct {
Client *Client
Request *Request
SoapAction string
Payload []byte
}
// doRequest makes new request to the server using the c.Method, c.URL and the body.
// body is enveloped in Do method
func (p *process) doRequest(url string) ([]byte, error) {
req, err := http.NewRequest("POST", url, bytes.NewBuffer(p.Payload))
if err != nil {
return nil, err
}
if p.Client.config != nil && p.Client.config.Dump {
dump, err := httputil.DumpRequestOut(req, true)
if err != nil {
return nil, err
}
p.Client.config.Logger.LogRequest(p.Request.Method, dump)
}
if p.Client.Username != "" && p.Client.Password != "" {
req.SetBasicAuth(p.Client.Username, p.Client.Password)
}
req.ContentLength = int64(len(p.Payload))
req.Header.Add("Content-Type", "text/xml;charset=UTF-8")
req.Header.Add("Accept", "text/xml")
if p.SoapAction != "" {
req.Header.Add("SOAPAction", p.SoapAction)
}
resp, err := p.httpClient().Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if p.Client.config != nil && p.Client.config.Dump {
dump, err := httputil.DumpResponse(resp, true)
if err != nil {
return nil, err
}
p.Client.config.Logger.LogResponse(p.Request.Method, dump)
}
if resp.StatusCode < 200 || resp.StatusCode >= 400 {
if !(p.Client.config != nil && p.Client.config.Dump) {
_, err := io.Copy(ioutil.Discard, resp.Body)
if err != nil {
return nil, err
}
}
return nil, errors.New("unexpected status code: " + resp.Status)
}
return ioutil.ReadAll(resp.Body)
}
func (p *process) httpClient() *http.Client {
if p.Client.HTTPClient != nil {
return p.Client.HTTPClient
}
return http.DefaultClient
}
// ErrorWithPayload error payload schema
type ErrorWithPayload struct {
error
Payload []byte
}
// GetPayloadFromError returns the payload of a ErrorWithPayload
func GetPayloadFromError(err error) []byte {
if err, ok := err.(ErrorWithPayload); ok {
return err.Payload
}
return nil
}
// SoapEnvelope struct
type SoapEnvelope struct {
XMLName struct{} `xml:"Envelope"`
Header SoapHeader
Body SoapBody
}
// SoapHeader struct
type SoapHeader struct {
XMLName struct{} `xml:"Header"`
Contents []byte `xml:",innerxml"`
}
// SoapBody struct
type SoapBody struct {
XMLName struct{} `xml:"Body"`
Contents []byte `xml:",innerxml"`
}