67 lines
1.2 KiB
Go
67 lines
1.2 KiB
Go
package api
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type Client struct {
|
|
URL string
|
|
Key string
|
|
client *http.Client
|
|
}
|
|
|
|
func New(url, key string) *Client {
|
|
return &Client{
|
|
URL: strings.TrimSuffix(url, "/"),
|
|
Key: key,
|
|
client: &http.Client{Timeout: time.Second * 2},
|
|
}
|
|
}
|
|
|
|
func (c *Client) Issue(id uint64) (*Issue, error) {
|
|
var resp IssueResponse
|
|
err := c.sendJSONRequest(http.MethodGet, "/issues/"+strconv.FormatUint(id, 10), nil, &resp)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if resp.IsError() {
|
|
return nil, resp
|
|
}
|
|
return resp.Issue, nil
|
|
}
|
|
|
|
func (c *Client) sendRequest(method, path string, body io.Reader) (*http.Response, error) {
|
|
req, err := http.NewRequest(method, c.URL+path, body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req.Header.Set("X-Redmine-API-Key", c.Key)
|
|
|
|
return c.client.Do(req)
|
|
}
|
|
|
|
func (c *Client) sendJSONRequest(method, path string, body, out interface{}) error {
|
|
var buf io.Reader
|
|
if body != nil {
|
|
data, err := json.Marshal(body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
buf = bytes.NewBuffer(data)
|
|
}
|
|
|
|
resp, err := c.sendRequest(method, path+".json", buf)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
defer func() { _ = resp.Body.Close() }()
|
|
return json.NewDecoder(resp.Body).Decode(out)
|
|
}
|