-
Notifications
You must be signed in to change notification settings - Fork 13
/
attachment.go
71 lines (56 loc) · 1.49 KB
/
attachment.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
package mixin
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
)
type Attachment struct {
AttachmentID string `json:"attachment_id"`
UploadURL string `json:"upload_url"`
ViewURL string `json:"view_url"`
}
func (c *Client) CreateAttachment(ctx context.Context) (*Attachment, error) {
var attachment Attachment
if err := c.Post(ctx, "/attachments", nil, &attachment); err != nil {
return nil, err
}
return &attachment, nil
}
func (c *Client) ShowAttachment(ctx context.Context, id string) (*Attachment, error) {
uri := fmt.Sprintf("/attachments/%s", id)
var attachment Attachment
if err := c.Get(ctx, uri, nil, &attachment); err != nil {
return nil, err
}
return &attachment, nil
}
var uploadClient = &http.Client{}
func UploadAttachmentTo(ctx context.Context, uploadURL string, file []byte) error {
req, err := http.NewRequest("PUT", uploadURL, bytes.NewReader(file))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/octet-stream")
req.Header.Add("x-amz-acl", "public-read")
req.Header.Add("Content-Length", strconv.Itoa(len(file)))
resp, err := uploadClient.Do(req)
if resp != nil {
_, _ = io.Copy(ioutil.Discard, resp.Body)
_ = resp.Body.Close()
}
if err != nil {
return err
}
if resp.StatusCode >= 300 {
return errors.New(resp.Status)
}
return nil
}
func UploadAttachment(ctx context.Context, attachment *Attachment, file []byte) error {
return UploadAttachmentTo(ctx, attachment.UploadURL, file)
}