-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
128 lines (95 loc) · 2.2 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
package updateApiClient
import (
"encoding/json"
"github.com/monaco-io/request"
"github.com/monaco-io/request/response"
"io"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"github.com/khorevaa/logos"
)
var log = logos.New("github.com/v8platform/updateApiClient")
const (
baseURL = "https://update-api.1c.ru"
userAgent = "1C+Enterprise/8.3"
)
type Client struct {
BaseURL string
Username string
Password string
}
func NewClient(username, password string) *Client {
return &Client{
baseURL,
username,
password,
}
}
type apiRequest struct {
path string
method string
data interface{}
}
func (c *Client) doFileRequest(fileRequestUrl string) (io.ReadCloser, error) {
req, err := http.NewRequest("GET", fileRequestUrl, nil)
if err != nil {
return nil, err
}
req.SetBasicAuth(c.Username, c.Password)
req.Header.Add("User-Agent", userAgent)
req.Header.Add("Content-Type", "application/json")
cj, _ := cookiejar.New(nil)
httpClient := &http.Client{
Jar: cj,
}
res, err := httpClient.Do(req)
if err != nil {
return nil, err
}
switch res.StatusCode {
case http.StatusBadRequest, http.StatusNotFound:
var err RequestError
body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
log.Fatal(readErr.Error())
return nil, readErr
}
jsonErr := json.Unmarshal(body, &err)
if jsonErr != nil {
log.Fatal(jsonErr.Error())
return nil, jsonErr
}
return nil, err
case http.StatusOK:
return res.Body, nil
}
return res.Body, nil
}
func (c *Client) doRequest(req apiRequest) (*response.Sugar, error) {
return c.doRawRequest(c.BaseURL, req)
}
func (c *Client) doRawRequest(baseURL string, req apiRequest) (*response.Sugar, error) {
client := request.Client{
URL: baseURL + req.path,
Method: req.method,
JSON: req.data,
Header: map[string]string{
"Content-Type": "application/json",
"User-Agent": userAgent,
},
}
resp := client.Send()
if !resp.OK() {
log.Error("Error while doRequest: " + resp.Error().Error())
return nil, resp.Error()
}
httpRes := resp.Response()
switch httpRes.StatusCode {
case http.StatusBadRequest, http.StatusNotFound:
var err RequestError
resp.Scan(&err)
return nil, err
}
return resp, nil
}