-
-
Notifications
You must be signed in to change notification settings - Fork 81
/
client.go
84 lines (72 loc) · 1.66 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
package redmine
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
type Client struct {
endpoint string
apikey string
*http.Client
Limit int
Offset int
}
var DefaultLimit int = -1 // "-1" means "No setting"
var DefaultOffset int = -1 //"-1" means "No setting"
func NewClient(endpoint, apikey string) *Client {
return &Client{endpoint, apikey, http.DefaultClient, DefaultLimit, DefaultOffset}
}
// URLWithFilter return string url by concat endpoint, path and filter
// err != nil when endpoin can not parse
func (c *Client) URLWithFilter(path string, f Filter) (string, error) {
var fullURL *url.URL
fullURL, err := url.Parse(c.endpoint)
if err != nil {
return "", err
}
fullURL.Path += path
if c.Limit > -1 {
f.AddPair("limit", strconv.Itoa(c.Limit))
}
if c.Offset > -1 {
f.AddPair("offset", strconv.Itoa(c.Offset))
}
fullURL.RawQuery = f.ToURLParams()
return fullURL.String(), nil
}
func (c *Client) getPaginationClause() string {
clause := ""
if c.Limit > -1 {
clause = clause + fmt.Sprintf("&limit=%v", c.Limit)
}
if c.Offset > -1 {
clause = clause + fmt.Sprintf("&offset=%v", c.Offset)
}
return clause
}
type errorsResult struct {
Errors []string `json:"errors"`
}
func errorFromResp(bodyDecoder *json.Decoder, httpStatus int) (err error) {
var er errorsResult
err = bodyDecoder.Decode(&er)
if err == nil { /* error from redmine */
return errors.New(strings.Join(er.Errors, "\n"))
}
if err == io.EOF { /* empty body */
err = errors.New(http.StatusText(httpStatus))
}
return
}
type IdName struct {
Id int `json:"id"`
Name string `json:"name"`
}
type Id struct {
Id int `json:"id"`
}