-
Notifications
You must be signed in to change notification settings - Fork 1
/
photo.go
111 lines (98 loc) · 2.49 KB
/
photo.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package snapas
import (
"bytes"
"encoding/json"
"fmt"
"github.com/writeas/impart"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"time"
)
type (
// Photo represents a photo on Snap.as.
Photo struct {
ID string `json:"id"`
Created time.Time `json:"created"`
Body *string `json:"body"`
AltText *string `json:"alt_text"`
Filename string `json:"filename"`
Size int64 `json:"size"`
URL string `json:"url"`
Album *Album `json:"album"`
}
// PhotoParams holds valid values for uploading photos.
PhotoParams struct {
FileName string
Body string
AltText string
// OrgAlias is the alias of the organization to upload to.
OrgAlias string
}
)
// UploadPhoto uploads a photo, and returns a Snap.as Photo. See:
// https://developers.snap.as/docs/api/#upload-a-photo
func (c *Client) UploadPhoto(sp *PhotoParams) (*Photo, error) {
f, err := os.Open(sp.FileName)
if err != nil {
return nil, fmt.Errorf("open file: %s", err)
}
defer f.Close()
body := &bytes.Buffer{}
w := multipart.NewWriter(body)
if sp.Body != "" {
err = w.WriteField("body", sp.Body)
if err != nil {
return nil, fmt.Errorf("write field 'body': %s", err)
}
}
if sp.AltText != "" {
err = w.WriteField("alt_text", sp.AltText)
if err != nil {
return nil, fmt.Errorf("write field 'alt_text': %s", err)
}
}
part, err := w.CreateFormFile("file", filepath.Base(f.Name()))
if err != nil {
return nil, fmt.Errorf("create form file: %s", err)
}
_, err = io.Copy(part, f)
if err != nil {
return nil, fmt.Errorf("copy file: %s", err)
}
err = w.Close()
if err != nil {
return nil, fmt.Errorf("close writer: %s", err)
}
orgBase := ""
if sp.OrgAlias != "" {
orgBase = "/organizations/" + sp.OrgAlias
}
url := fmt.Sprintf("%s%s%s", c.Config.BaseURL, orgBase, "/photos/upload")
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, fmt.Errorf("create request: %s", err)
}
req.Header.Add("User-Agent", c.Config.UserAgent)
req.Header.Add("Content-Type", w.FormDataContentType())
req.Header.Add("Authorization", c.Token)
resp, err := c.Config.Client.Do(req)
if err != nil {
return nil, fmt.Errorf("request: %s", err)
}
defer resp.Body.Close()
env := &impart.Envelope{
Code: resp.StatusCode,
Data: &Photo{},
}
err = json.NewDecoder(resp.Body).Decode(&env)
if err != nil {
return nil, err
}
if env.Code != http.StatusCreated {
return nil, fmt.Errorf("%s", env.ErrorMessage)
}
return env.Data.(*Photo), nil
}