forked from educlos/testrail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
89 lines (74 loc) · 1.81 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
// testrail provides a go api for testrail
package testrail
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
)
// A Client stores the client informations
// and implement all the api functions
// to communicate with testrail
type Client struct {
url string
username string
password string
httpClient *http.Client
}
// NewClient returns a new client
// with the given credential
// for the given testrail domain
func NewClient(url, username, password string) (c *Client) {
c = &Client{}
c.username = username
c.password = password
c.url = url
if !strings.HasSuffix(c.url, "/") {
c.url += "/"
}
c.url += "index.php?/api/v2/"
c.httpClient = &http.Client{}
return
}
// sendRequest sends a request of type "method"
// to the url "client.url+uri" and with optional data "data"
// Returns an error if any and the optional data "v"
func (c *Client) sendRequest(method, uri string, data, v interface{}) error {
var body io.Reader
if data != nil {
jsonReq, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("marshaling data: %s", err)
}
body = bytes.NewBuffer(jsonReq)
}
req, err := http.NewRequest(method, c.url+uri, body)
if err != nil {
return err
}
req.SetBasicAuth(c.username, c.password)
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
jsonCnt, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("reading: %s", err)
}
if resp.StatusCode >= http.StatusBadRequest {
return fmt.Errorf("response: status: %q, body: %s", resp.Status, jsonCnt)
}
if v != nil {
err = json.Unmarshal(jsonCnt, v)
if err != nil {
return fmt.Errorf("unmarshaling response: %s", err)
}
}
return nil
}