-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathclient.go
252 lines (229 loc) · 6.77 KB
/
client.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
// Package soap provides a SOAP HTTP client.
package soap
import (
"bytes"
"context"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"reflect"
"golang.org/x/net/html/charset"
)
// XSINamespace is a link to the XML Schema instance namespace.
const XSINamespace = "http://www.w3.org/2001/XMLSchema-instance"
var xmlTyperType reflect.Type = reflect.TypeOf((*XMLTyper)(nil)).Elem()
// A RoundTripper executes a request passing the given req as the SOAP
// envelope body. The HTTP response is then de-serialized onto the resp
// object. Returns error in case an error occurs serializing req, making
// the HTTP request, or de-serializing the response.
type RoundTripper interface {
RoundTrip(req, resp Message) error
RoundTripSoap12(action string, req, resp Message) error
}
// Message is an opaque type used by the RoundTripper to carry XML
// documents for SOAP.
type Message interface{}
// Header is an opaque type used as the SOAP Header element in requests.
type Header interface{}
// AuthHeader is a Header to be encoded as the SOAP Header element in
// requests, to convey credentials for authentication.
type AuthHeader struct {
Namespace string `xml:"xmlns:ns,attr"`
Username string `xml:"ns:username"`
Password string `xml:"ns:password"`
}
// Client is a SOAP client.
type Client struct {
URL string // URL of the server
UserAgent string // User-Agent header will be added to each request
Namespace string // SOAP Namespace
URNamespace string // Uniform Resource Namespace
ThisNamespace string // SOAP This-Namespace (tns)
ExcludeActionNamespace bool // Include Namespace to SOAP Action header
Envelope string // Optional SOAP Envelope
Header Header // Optional SOAP Header
ContentType string // Optional Content-Type (default text/xml)
Config *http.Client // Optional HTTP client
Pre func(*http.Request) // Optional hook to modify outbound requests
Post func(*http.Response) // Optional hook to snoop inbound responses
Ctx context.Context // Optional variable to allow Context Tracking.
}
// XMLTyper is an abstract interface for types that can set an XML type.
type XMLTyper interface {
SetXMLType()
}
func setXMLType(v reflect.Value) {
if !v.IsValid() {
return
}
switch v.Type().Kind() {
case reflect.Interface:
setXMLType(v.Elem())
case reflect.Ptr:
if v.IsNil() {
break
}
ok := v.Type().Implements(xmlTyperType)
if ok {
v.MethodByName("SetXMLType").Call(nil)
}
setXMLType(v.Elem())
case reflect.Slice:
for i := 0; i < v.Len(); i++ {
setXMLType(v.Index(i))
}
case reflect.Struct:
for i := 0; i < v.NumField(); i++ {
if v.Field(i).CanAddr() {
setXMLType(v.Field(i).Addr())
} else {
setXMLType(v.Field(i))
}
}
}
}
func doRoundTrip(c *Client, setHeaders func(*http.Request), in, out Message) error {
setXMLType(reflect.ValueOf(in))
req := &Envelope{
EnvelopeAttr: c.Envelope,
URNAttr: c.URNamespace,
NSAttr: c.Namespace,
TNSAttr: c.ThisNamespace,
XSIAttr: XSINamespace,
Header: c.Header,
Body: in,
}
if req.EnvelopeAttr == "" {
req.EnvelopeAttr = "http://schemas.xmlsoap.org/soap/envelope/"
}
if req.NSAttr == "" {
req.NSAttr = c.URL
}
if req.TNSAttr == "" {
req.TNSAttr = req.NSAttr
}
var b bytes.Buffer
err := xml.NewEncoder(&b).Encode(req)
if err != nil {
return err
}
cli := c.Config
if cli == nil {
cli = http.DefaultClient
}
r, err := http.NewRequest("POST", c.URL, &b)
if err != nil {
return err
}
setHeaders(r)
if c.Pre != nil {
c.Pre(r)
}
if c.Ctx != nil {
r = r.WithContext(c.Ctx)
}
resp, err := cli.Do(r)
if err != nil {
return err
}
defer resp.Body.Close()
if c.Post != nil {
c.Post(resp)
}
if resp.StatusCode != http.StatusOK {
// read only the first MiB of the body in error case
limReader := io.LimitReader(resp.Body, 1024*1024)
body, _ := ioutil.ReadAll(limReader)
return &HTTPError{
StatusCode: resp.StatusCode,
Status: resp.Status,
Msg: string(body),
}
}
marshalStructure := struct {
XMLName xml.Name `xml:"Envelope"`
Body Message
}{Body: out}
decoder := xml.NewDecoder(resp.Body)
decoder.CharsetReader = charset.NewReaderLabel
return decoder.Decode(&marshalStructure)
}
// RoundTrip implements the RoundTripper interface.
func (c *Client) RoundTrip(in, out Message) error {
headerFunc := func(r *http.Request) {
if c.UserAgent != "" {
r.Header.Add("User-Agent", c.UserAgent)
}
var actionName, soapAction string
if in != nil {
soapAction = reflect.TypeOf(in).Elem().Name()
}
ct := c.ContentType
if ct == "" {
ct = "text/xml"
}
r.Header.Set("Content-Type", ct)
if in != nil {
if c.ExcludeActionNamespace {
actionName = soapAction
} else {
actionName = fmt.Sprintf("%s/%s", c.Namespace, soapAction)
}
r.Header.Add("SOAPAction", actionName)
}
}
return doRoundTrip(c, headerFunc, in, out)
}
// RoundTripWithAction implements the RoundTripper interface for SOAP clients
// that need to set the SOAPAction header.
func (c *Client) RoundTripWithAction(soapAction string, in, out Message) error {
headerFunc := func(r *http.Request) {
if c.UserAgent != "" {
r.Header.Add("User-Agent", c.UserAgent)
}
var actionName string
ct := c.ContentType
if ct == "" {
ct = "text/xml"
}
r.Header.Set("Content-Type", ct)
if in != nil {
if c.ExcludeActionNamespace {
actionName = soapAction
} else {
actionName = fmt.Sprintf("%s/%s", c.Namespace, soapAction)
}
r.Header.Add("SOAPAction", actionName)
}
}
return doRoundTrip(c, headerFunc, in, out)
}
// RoundTripSoap12 implements the RoundTripper interface for SOAP 1.2.
func (c *Client) RoundTripSoap12(action string, in, out Message) error {
headerFunc := func(r *http.Request) {
r.Header.Add("Content-Type", fmt.Sprintf("application/soap+xml; charset=utf-8; action=\"%s\"", action))
}
return doRoundTrip(c, headerFunc, in, out)
}
// HTTPError is detailed soap http error
type HTTPError struct {
StatusCode int
Status string
Msg string
}
func (e *HTTPError) Error() string {
return fmt.Sprintf("%q: %q", e.Status, e.Msg)
}
// Envelope is a SOAP envelope.
type Envelope struct {
XMLName xml.Name `xml:"SOAP-ENV:Envelope"`
EnvelopeAttr string `xml:"xmlns:SOAP-ENV,attr"`
NSAttr string `xml:"xmlns:ns,attr"`
TNSAttr string `xml:"xmlns:tns,attr,omitempty"`
URNAttr string `xml:"xmlns:urn,attr,omitempty"`
XSIAttr string `xml:"xmlns:xsi,attr,omitempty"`
Header Message `xml:"SOAP-ENV:Header"`
Body Message `xml:"SOAP-ENV:Body"`
}