-
Notifications
You must be signed in to change notification settings - Fork 0
/
mgo_service_client.go
84 lines (72 loc) · 1.8 KB
/
mgo_service_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
package queue_reader
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"time"
)
type client struct {
client *http.Client
}
// GetClient возвращает http.Client с установленным таймаутом в 10 секунд
func GetClient(timeOut time.Duration) *client {
return &client{
client: &http.Client{Timeout: timeOut},
}
}
// SendData отправляет массив байтов на сервис
func (cli *client) SendData(url string, content XmlContent) error {
js, err := json.Marshal(content)
if err != nil {
return err
}
req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(js))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
resp, err := cli.client.Do(req)
req.Body.Close()
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
respBuf := bytes.NewBuffer(make([]byte, 0, resp.ContentLength))
respBuf.ReadFrom(resp.Body)
defer func() {
resp.Body.Close()
respBuf.Truncate(0)
}()
return errors.New(respBuf.String())
}
return nil
}
// XmlToJSON send xmlContent to service and return JSON
func (cli *client) XmlToJSON(url string, content XmlContent) ([]byte, error) {
js, err := json.Marshal(content)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(js))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := cli.client.Do(req)
defer req.Body.Close()
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
respBuf := bytes.NewBuffer(make([]byte, 0, resp.ContentLength))
respBuf.ReadFrom(resp.Body)
defer func() {
resp.Body.Close()
respBuf.Truncate(0)
}()
return nil, errors.New(respBuf.String())
}
return ioutil.ReadAll(resp.Body)
}