From 2c4c9fdde6e693dfd92bbf9697d33c502e0a268a Mon Sep 17 00:00:00 2001 From: Justin Hawkins Date: Mon, 11 Oct 2021 22:48:49 +1030 Subject: [PATCH] Handle "entity too large" errors immediately instead of retrying. --- upload/upload.go | 5 +++++ upload/upload_test.go | 26 ++++++++++++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/upload/upload.go b/upload/upload.go index 12ff4a5..d5143b7 100644 --- a/upload/upload.go +++ b/upload/upload.go @@ -141,6 +141,11 @@ func (u *Upload) processUpload() error { sleepForRetries(retriesRemaining) continue } else { + if resp.StatusCode == 413 { + // just fail immediately, we know this means the file was too big + daulog.SendLog("413 received - file too large", daulog.LogTypeError) + return errors.New("received 413 - file too large") + } if resp.StatusCode != 200 { // {"message": "Request entity too large", "code": 40005} diff --git a/upload/upload_test.go b/upload/upload_test.go index 055744e..ad080ac 100644 --- a/upload/upload_test.go +++ b/upload/upload_test.go @@ -4,8 +4,8 @@ import ( "bytes" "io/ioutil" "net/http" - "testing" "os" + "testing" // "github.com/tardisx/discord-auto-upload/config" ) @@ -26,6 +26,14 @@ func DoGoodUpload(req *http.Request) (*http.Response, error) { }, nil } +func DoTooBigUpload(req *http.Request) (*http.Response, error) { + r := ioutil.NopCloser(bytes.NewReader([]byte(`{"message": "Request entity too large", "code": 40005}`))) + return &http.Response{ + StatusCode: 413, + Body: r, + }, nil +} + func TestSuccessfulUpload(t *testing.T) { // create temporary file, processUpload requires that it exists, even though // we will not really be uploading it here @@ -43,5 +51,19 @@ func TestSuccessfulUpload(t *testing.T) { if u.Url != "https://cdn.discordapp.com/attachments/849615269706203171/851092588332449812/dau480457962.png" { t.Error("URL wrong") } - +} + +func TestTooBigUpload(t *testing.T) { + // create temporary file, processUpload requires that it exists, even though + // we will not really be uploading it here + f, _ := os.CreateTemp("", "dautest-upload-*") + defer os.Remove(f.Name()) + u := Upload{webhookURL: "https://127.0.0.1/", originalFilename: f.Name()} + u.Client = &MockClient{DoFunc: DoTooBigUpload} + err := u.processUpload() + if err == nil { + t.Error("error did not occur?") + } else if err.Error() != "received 413 - file too large" { + t.Errorf("wrong error occurred: %s", err.Error()) + } }