Skip to content

Commit 4f71ea8

Browse files
committed
Upload file use synchronous in-memory pipe
1 parent 064186f commit 4f71ea8

File tree

1 file changed

+19
-13
lines changed

1 file changed

+19
-13
lines changed

pkg/infura/infura.go

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
package infura
22

33
import (
4-
"bytes"
54
"encoding/json"
65
"fmt"
76
"io"
87
"io/ioutil"
98
"mime/multipart"
109
"net/http"
1110
"os"
11+
fp "path/filepath"
1212
"time"
1313
)
1414

@@ -21,29 +21,35 @@ const (
2121

2222
func PinFile(filepath string) (string, error) {
2323
uri := fmt.Sprintf("%s://%s:%d/api/v0/add", INFURA_PROTOCAL, INFURA_HOST, INFURA_PORT)
24-
body := &bytes.Buffer{}
25-
writer := multipart.NewWriter(body)
26-
defer writer.Close()
2724

28-
part, err := writer.CreateFormFile("file", filepath)
29-
if err != nil {
30-
return "", err
31-
}
3225
file, err := os.Open(filepath)
3326
if err != nil {
3427
return "", err
3528
}
3629
defer file.Close()
3730

38-
if _, err = io.Copy(part, file); err != nil {
39-
return "", err
40-
}
31+
r, w := io.Pipe()
32+
m := multipart.NewWriter(w)
33+
34+
go func() {
35+
defer w.Close()
36+
defer m.Close()
37+
38+
part, err := m.CreateFormFile("file", fp.Base(file.Name()))
39+
if err != nil {
40+
return
41+
}
42+
43+
if _, err = io.Copy(part, file); err != nil {
44+
return
45+
}
46+
}()
4147

4248
client := &http.Client{
4349
Timeout: 30 * time.Second,
4450
}
45-
req, err := http.NewRequest(http.MethodPost, uri, body)
46-
req.Header.Add("Content-Type", writer.FormDataContentType())
51+
req, err := http.NewRequest(http.MethodPost, uri, r)
52+
req.Header.Add("Content-Type", m.FormDataContentType())
4753
resp, err := client.Do(req)
4854
if err != nil {
4955
return "", err

0 commit comments

Comments
 (0)