mirror of
https://github.com/duke-git/lancet.git
synced 2026-11-16 05:12:11 +08:00
fix(package): [netutil] handle upload responses (#389)
This commit is contained in:
1 parent
febd1030af
commit
be9b167a9b
2 files changed
+46
-1
No files matched your search
+5
-1
@@ -269,10 +269,14 @@ func UploadFile(filepath string, server string) (bool, error) {
|
|||||||
contentType := writer.FormDataContentType()
|
contentType := writer.FormDataContentType()
|
||||||
writer.Close()
|
writer.Close()
|
||||||
|
|
||||||
_, err = http.Post(server, contentType, bodyBuffer)
|
resp, err := http.Post(server, contentType, bodyBuffer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||||
|
return false, fmt.Errorf("upload failed: %s", resp.Status)
|
||||||
|
}
|
||||||
|
|
||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package netutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
type uploadResponseBody struct {
|
||||||
|
io.Reader
|
||||||
|
closed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *uploadResponseBody) Close() error { b.closed = true; return nil }
|
||||||
|
|
||||||
|
type uploadTransport struct{ response *http.Response }
|
||||||
|
|
||||||
|
func (t uploadTransport) RoundTrip(*http.Request) (*http.Response, error) { return t.response, nil }
|
||||||
|
|
||||||
|
func TestUploadFileResponse(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "upload.txt")
|
||||||
|
if err := os.WriteFile(path, []byte("content"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
original := http.DefaultClient
|
||||||
|
defer func() { http.DefaultClient = original }()
|
||||||
|
for _, status := range []int{http.StatusCreated, http.StatusInternalServerError} {
|
||||||
|
body := &uploadResponseBody{Reader: strings.NewReader("response")}
|
||||||
|
http.DefaultClient = &http.Client{Transport: uploadTransport{&http.Response{StatusCode: status, Body: body}}}
|
||||||
|
ok, err := UploadFile(path, "https://example.com/upload")
|
||||||
|
if ok != (status == http.StatusCreated) || (err != nil) != (status != http.StatusCreated) {
|
||||||
|
t.Errorf("status %d: got %v, %v", status, ok, err)
|
||||||
|
}
|
||||||
|
if !body.closed {
|
||||||
|
t.Errorf("status %d: response body was not closed", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user