-
Notifications
You must be signed in to change notification settings - Fork 6
/
upload.go
69 lines (62 loc) · 1.38 KB
/
upload.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
// Wrapper around the 'upload' endpoint
package telegraph
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
)
var baseUploadURL = "https://graph.org/upload"
type uploadResult struct {
Source []source
}
type source struct {
Src string `json:"src"`
}
type errorUpload struct {
Error string `json:"error"`
}
// Upload photo/video to Telegra.ph on the '/upload' endpoint.
// Media type should either be "video" or "photo". "Animation" is considered "video" here.
func Upload(f io.Reader, mediaType string) (string, error) {
b := &bytes.Buffer{}
w := multipart.NewWriter(b)
var name string
if mediaType == "video" {
name = "file.mp4"
} else {
name = "file.jpg"
}
part, err := w.CreateFormFile(mediaType, name)
if err != nil {
return "", err
}
io.Copy(part, f)
w.Close()
r, err := http.NewRequest("POST", baseUploadURL, bytes.NewReader(b.Bytes()))
if err != nil {
return "", err
}
r.Header.Set("Content-Type", w.FormDataContentType())
c := &http.Client{}
resp, err := c.Do(r)
if err != nil {
return "", err
}
content, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return "", err
}
var jsonData uploadResult
json.Unmarshal(content, &jsonData.Source)
if jsonData.Source == nil {
var err errorUpload
json.Unmarshal(content, &err)
return "", fmt.Errorf(err.Error)
}
return jsonData.Source[0].Src, err
}