126
|
1 |
package gondole |
|
2 |
|
|
3 |
import ( |
|
4 |
"bytes" |
|
5 |
"encoding/json" |
|
6 |
"fmt" |
|
7 |
"io" |
|
8 |
"mime/multipart" |
|
9 |
"os" |
|
10 |
"path/filepath" |
|
11 |
|
|
12 |
"github.com/sendgrid/rest" |
|
13 |
) |
|
14 |
|
|
15 |
// UploadMedia uploads the given file and returns an attachment |
|
16 |
func (g *Client) UploadMedia(filePath string) (*Attachment, error) { |
|
17 |
var b bytes.Buffer |
|
18 |
|
|
19 |
if filePath == "" { |
|
20 |
return nil, ErrInvalidParameter |
|
21 |
} |
|
22 |
|
|
23 |
f, err := os.Open(filePath) |
|
24 |
if err != nil { |
|
25 |
return nil, fmt.Errorf("cannot read file: %s", err.Error()) |
|
26 |
} |
|
27 |
defer f.Close() |
|
28 |
|
|
29 |
w := multipart.NewWriter(&b) |
|
30 |
formWriter, err := w.CreateFormFile("file", filepath.Base(filePath)) |
|
31 |
if err != nil { |
|
32 |
return nil, fmt.Errorf("media upload: cannot create form: %s", err.Error()) |
|
33 |
} |
|
34 |
if _, err = io.Copy(formWriter, f); err != nil { |
|
35 |
return nil, fmt.Errorf("media upload: cannot create form: %s", err.Error()) |
|
36 |
} |
|
37 |
|
|
38 |
w.Close() |
|
39 |
|
|
40 |
req := g.prepareRequest("media", rest.Post, nil) |
|
41 |
req.Headers["Content-Type"] = w.FormDataContentType() |
|
42 |
req.Body = b.Bytes() |
|
43 |
|
|
44 |
/* |
|
45 |
reqObj, err := rest.BuildRequestObject(req) |
|
46 |
if err != nil { |
|
47 |
return nil, fmt.Errorf("cannot build stream request: %s", err.Error()) |
|
48 |
} |
|
49 |
|
|
50 |
resp, err := rest.MakeRequest(reqObj) |
|
51 |
if err != nil { |
|
52 |
return nil, fmt.Errorf("cannot open stream: %s", err.Error()) |
|
53 |
} |
|
54 |
if resp.StatusCode != 200 { |
|
55 |
resp.Body.Close() |
|
56 |
return nil, errors.New(resp.Status) |
|
57 |
} |
|
58 |
return resp, nil |
|
59 |
*/ |
|
60 |
|
|
61 |
// Make API call |
|
62 |
r, err := restAPI(req) |
|
63 |
if err != nil { |
|
64 |
return nil, fmt.Errorf("media upload failed: %s", err.Error()) |
|
65 |
} |
|
66 |
|
|
67 |
// Check for error reply |
|
68 |
var errorResult Error |
|
69 |
if err := json.Unmarshal([]byte(r.Body), &errorResult); err == nil { |
|
70 |
// The empty object is not an error |
|
71 |
if errorResult.Text != "" { |
|
72 |
return nil, fmt.Errorf("%s", errorResult.Text) |
|
73 |
} |
|
74 |
} |
|
75 |
|
|
76 |
// Not an error reply; let's unmarshal the data |
|
77 |
var attachment Attachment |
|
78 |
err = json.Unmarshal([]byte(r.Body), &attachment) |
|
79 |
if err != nil { |
|
80 |
return nil, fmt.Errorf("cannot decode API response (media): %s", err.Error()) |
|
81 |
} |
|
82 |
return &attachment, nil |
|
83 |
} |