-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrequest.go
97 lines (79 loc) · 2.17 KB
/
request.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
package polyanalyst6api
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/Megaputer/polyanalyst6api-go/parameters"
)
type request struct {
httpReq *http.Request
// session *Session
// path string
// reqType string
// params parameters.Full
}
type serverErrorData struct {
Content ServerError `json:"error"`
}
func createRequest(path string, reqType string, params parameters.Full) (request, error) {
var (
retReq request
err error
)
// turning url paras to RFC 3986 compatible string
urlParams := strings.Replace(params.URLParams.Encode(), "+", "%20", -1)
url := path + "?" + urlParams
req, err := http.NewRequest(reqType, url, bytes.NewBuffer(params.BodyParams))
if err != nil {
return retReq, fmt.Errorf("building request error: %s", err)
}
return request{httpReq: req}, nil
}
func (r *request) UseSession(s *Session) {
cookie := http.Cookie{Name: "sid", Value: s.SID}
r.httpReq.AddCookie(&cookie)
}
func (r request) Perform() (RequestResult, error) {
var result RequestResult
client := &http.Client{
Timeout: RequestTimeout,
}
resp, err := client.Do(r.httpReq)
if err != nil {
return result, fmt.Errorf("request execution error: %w", err)
}
defer closeBody(resp)
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return result, fmt.Errorf("failed to read response body: %w", err)
}
if resp.StatusCode != 200 && resp.StatusCode != 202 {
var errorData serverErrorData
err = json.Unmarshal(data, &errorData)
if err != nil {
return result, fmt.Errorf("failed to parse server error [%s]: %w", data, err)
}
return result, errorData.Content
}
result.Body = data
locURL, err := resp.Location()
if err == nil {
params, err := url.ParseQuery(locURL.RawQuery)
if err == nil {
execWaveStrings, ok := params["executionWave"]
if ok && len(execWaveStrings) > 0 {
execWaveInt, err := strconv.Atoi(execWaveStrings[0])
if err == nil {
result.Additions.ExecutionWaveID = new(int)
result.Additions.ExecutionWaveID = &execWaveInt
}
}
}
}
return result, nil
}