-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
96 lines (76 loc) · 2.38 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
package fscr
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net/http"
"go.uber.org/multierr"
)
// ProductionURL is the URL of the production EET system.
const ProductionURL = "https://prod.eet.cz/eet/services/EETServiceSOAP/v3"
// PlaygroundURL is the URL of the playground EET system.
const PlaygroundURL = "https://pg.eet.cz/eet/services/EETServiceSOAP/v3"
const soapAction = "http://fs.mfcr.cz/eet/OdeslaniTrzby"
// Client represents a client to communicate with the FSCR servers.
type Client interface {
Ping() error
Do(ctx context.Context, reqBody []byte) ([]byte, error)
}
type client struct {
c *http.Client
url string
}
// NewClient returns a Client implementation.
func NewClient(c *http.Client, url string) Client {
return &client{
c: c,
url: url,
}
}
// Ping pings the host and returns the status code of the HTTP response.
func (c *client) Ping() error {
resp, err := c.c.Head(c.url)
if err != nil {
return fmt.Errorf("ping %s: %w", c.url, err)
}
defer multierr.AppendInvoke(&err, multierr.Close(resp.Body))
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("status code not OK (200): %s", http.StatusText(resp.StatusCode))
}
return nil
}
// Do makes a valid SOAP request to the FSCR servers with the request body reqBody and
// redirects the response body to respBody.
func (c *client) Do(ctx context.Context, reqBody []byte) (respBody []byte, err error) {
req, err := createRequest(ctx, c.url, reqBody)
if err != nil {
return nil, fmt.Errorf("construct http request: %w", err)
}
resp, err := c.doHTTP(req)
if err != nil {
return nil, fmt.Errorf("handle request: %w", err)
}
defer multierr.AppendInvoke(&err, multierr.Close(resp.Body))
respBody, err = ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read response body: %w", err)
}
return respBody, err
}
func (c *client) doHTTP(req *http.Request) (*http.Response, error) {
resp, err := c.c.Do(req)
if err != nil {
return nil, fmt.Errorf("send request: %w", err)
}
return resp, nil
}
func createRequest(ctx context.Context, url string, reqBody []byte) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(reqBody))
if err != nil {
return nil, fmt.Errorf("create a new http request: %w", err)
}
req.Header.Set("SOAPAction", soapAction)
req.Header.Set("Content-Type", "text/xml; charset=\"utf-8\"")
return req, nil
}