forked from mattn/go-redmine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uploads.go
53 lines (48 loc) · 1.07 KB
/
uploads.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
package redmine
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"strings"
)
type uploadResponse struct {
Upload Upload `json:"upload"`
}
type Upload struct {
Token string `json:"token"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
}
func (c *Client) Upload(filename string) (*Upload, error) {
content, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", c.endpoint+"/uploads.json?key="+c.apikey, bytes.NewBuffer(content))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/octet-stream")
res, err := c.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
decoder := json.NewDecoder(res.Body)
var r uploadResponse
if res.StatusCode != 201 {
var er errorsResult
err = decoder.Decode(&er)
if err == nil {
err = errors.New(strings.Join(er.Errors, "\n"))
}
} else {
err = decoder.Decode(&r)
}
if err != nil {
return nil, err
}
return &r.Upload, nil
}