-
Notifications
You must be signed in to change notification settings - Fork 0
/
input_file.go
100 lines (83 loc) · 2 KB
/
input_file.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
package tg
import (
"bytes"
"encoding/json"
"io"
"os"
"path/filepath"
)
// InputFile represents the file that should be uploaded to the telegram.
type InputFile struct {
// Filename
Name string
// Body of file
Body io.Reader
addr string
}
func (file *InputFile) setAddr(addr string) {
file.addr = addr
}
func (file *InputFile) MarshalJSON() ([]byte, error) {
return json.Marshal(file.addr)
}
// NewInputFile creates the InputFile from provided name and body reader.
func NewInputFile(name string, body io.Reader) *InputFile {
return &InputFile{
Name: name,
Body: body,
}
}
// NewInputFileBytes creates input file from provided name.
//
// Example:
// file := NewInputFileBytes("test.txt", []byte("test, test, test..."))
func NewInputFileBytes(name string, body []byte) *InputFile {
return NewInputFile(
name,
bytes.NewReader(body),
)
}
// NewInputFileLocal creates the InputFile from provided local file.
// This method just open file by provided path.
// So, you should close it AFTER send.
//
// Example:
//
// file, err := NewInputFileLocal("test.png")
// if err != nil {
// return err
// }
// defer file.Close()
//
func NewInputFileLocal(path string) (*InputFile, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
return NewInputFile(
filepath.Base(file.Name()),
file,
), nil
}
// NewInputFileLocalBuffer creates the InputFile from provided local file path.
// This function copy the file to the buffer in memory, so you do not need to close it.
func NewInputFileLocalBuffer(path string) (*InputFile, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
name := filepath.Base(file.Name())
body := &bytes.Buffer{}
if _, err := io.Copy(body, file); err != nil {
return nil, err
}
return NewInputFile(name, body), nil
}
// Close call close method on body if it implements io.ReadCloser,
// else - do nothing.
func (file *InputFile) Close() error {
if body, ok := file.Body.(io.ReadCloser); ok {
return body.Close()
}
return nil
}