|
2 | 2 | package volumes |
3 | 3 |
|
4 | 4 | import ( |
| 5 | + "bytes" |
5 | 6 | "encoding/json" |
6 | 7 | "fmt" |
7 | 8 | "io" |
8 | 9 | "mime/multipart" |
9 | 10 | "net/http" |
10 | 11 | "net/url" |
| 12 | + "strings" |
11 | 13 |
|
12 | 14 | drycc "github.com/drycc/controller-sdk-go" |
13 | 15 | "github.com/drycc/controller-sdk-go/api" |
@@ -42,32 +44,29 @@ func GetFile(c *drycc.Client, appID, volumeID, path string) (*http.Response, err |
42 | 44 | } |
43 | 45 |
|
44 | 46 | // Put file to an app's volume. |
45 | | -func PostFile(c *drycc.Client, appID, volumeID, volumePath, name string, reader io.Reader) (*http.Response, error) { |
46 | | - pr, pw := io.Pipe() |
47 | | - writer := multipart.NewWriter(pw) |
48 | | - go func() { |
49 | | - if err := writer.WriteField("path", volumePath); err != nil { |
50 | | - pw.CloseWithError(err) |
51 | | - return |
52 | | - } |
53 | | - part, err := writer.CreateFormFile("file", name) |
54 | | - if err != nil { |
55 | | - pw.CloseWithError(err) |
56 | | - return |
57 | | - } |
58 | | - _, err = io.Copy(part, reader) |
59 | | - if err != nil { |
60 | | - pw.CloseWithError(err) |
61 | | - return |
62 | | - } |
63 | | - pw.CloseWithError(writer.Close()) |
64 | | - }() |
| 47 | +func PostFile(c *drycc.Client, appID, volumeID, volumePath, name string, size int64, reader io.Reader) (*http.Response, error) { |
65 | 48 |
|
| 49 | + buffer := new(bytes.Buffer) |
| 50 | + writer := multipart.NewWriter(buffer) |
| 51 | + if err := writer.WriteField("path", volumePath); err != nil { |
| 52 | + return nil, err |
| 53 | + } |
| 54 | + if _, err := writer.CreateFormFile("file", name); err != nil { |
| 55 | + return nil, err |
| 56 | + } |
| 57 | + size += int64(buffer.Len()) |
| 58 | + head := strings.NewReader(buffer.String()) |
| 59 | + buffer.Reset() |
| 60 | + writer.Close() |
| 61 | + bottom := strings.NewReader(buffer.String()) |
| 62 | + size += int64(buffer.Len()) |
66 | 63 | u := fmt.Sprintf("/v2/apps/%s/volumes/%s/client/", appID, volumeID) |
67 | | - r, err := c.NewRequest("POST", u, pr) |
| 64 | + |
| 65 | + r, err := c.NewRequest("POST", u, io.MultiReader(head, reader, bottom)) |
68 | 66 | if err != nil { |
69 | 67 | return nil, err |
70 | 68 | } |
| 69 | + r.ContentLength = size |
71 | 70 | r.Header.Add("Content-Type", writer.FormDataContentType()) |
72 | 71 | return c.Do(r) |
73 | 72 | } |
|
0 commit comments