-
Notifications
You must be signed in to change notification settings - Fork 114
/
upload.go
110 lines (97 loc) · 2.35 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
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
package null
import (
"bytes"
"fmt"
"github.com/Mikubill/transfer/apis"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"strconv"
)
const upload = "https://0x0.st/"
func (b *null) DoUpload(name string, size int64, file io.Reader) error {
body, err := b.newMultipartUpload(uploadConfig{
fileSize: size,
fileName: name,
fileReader: file,
debug: apis.DebugMode,
})
if err != nil {
return fmt.Errorf("upload returns error: %s", err)
}
b.resp = string(body[:len(body)-1])
return nil
}
func (b *null) PostUpload(string, int64) (string, error) {
fmt.Printf("Download Link: %s\n", b.resp)
return b.resp, nil
}
func (b null) newMultipartUpload(config uploadConfig) ([]byte, error) {
if config.debug {
log.Printf("start upload")
}
client := http.Client{}
byteBuf := &bytes.Buffer{}
writer := multipart.NewWriter(byteBuf)
_, err := writer.CreateFormFile("file", config.fileName)
if err != nil {
return nil, err
}
writerLength := byteBuf.Len()
writerBody := make([]byte, writerLength)
_, _ = byteBuf.Read(writerBody)
_ = writer.Close()
lastBoundary := fmt.Sprintf("\r\n--%s--\r\n", writer.Boundary())
totalSize := int64(writerLength) + config.fileSize + int64(len(lastBoundary))
partR, partW := io.Pipe()
go func() {
_, _ = partW.Write(writerBody)
for {
buf := make([]byte, 256)
nr, err := io.ReadFull(config.fileReader, buf)
if nr <= 0 {
break
}
if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
fmt.Println(err)
break
}
if nr > 0 {
_, _ = partW.Write(buf[:nr])
}
}
_, _ = fmt.Fprintf(partW, lastBoundary)
_ = partW.Close()
}()
req, err := http.NewRequest("POST", upload, partR)
if err != nil {
return nil, err
}
req.ContentLength = totalSize
req.Header.Set("content-length", strconv.FormatInt(totalSize, 10))
req.Header.Set("content-type", fmt.Sprintf("multipart/form-data; boundary=%s", writer.Boundary()))
if config.debug {
log.Printf("header: %v", req.Header)
}
resp, err := client.Do(req)
if err != nil {
if config.debug {
log.Printf("do requests returns error: %v", err)
}
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
if config.debug {
log.Printf("read response returns: %v", err)
}
return nil, err
}
_ = resp.Body.Close()
if config.debug {
log.Printf("returns: %v", string(body))
}
return body, nil
}