From 193b0d3926696d4fe0a61f2b2bc0161e94ed9aa2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torjus=20H=C3=A5kestad?= Date: Thu, 20 Jan 2022 23:17:09 +0100 Subject: [PATCH] Use client for upload action --- cmd/client/actions/actions.go | 57 ++++++++--------------------------- 1 file changed, 13 insertions(+), 44 deletions(-) diff --git a/cmd/client/actions/actions.go b/cmd/client/actions/actions.go index 1954b76..00b256a 100644 --- a/cmd/client/actions/actions.go +++ b/cmd/client/actions/actions.go @@ -5,8 +5,6 @@ import ( "context" "encoding/json" "fmt" - "io" - "mime/multipart" "net/http" "os" "strings" @@ -14,61 +12,32 @@ import ( "time" "git.t-juice.club/torjus/gpaste/api" - "github.com/google/uuid" + "git.t-juice.club/torjus/gpaste/client" + "git.t-juice.club/torjus/gpaste/files" "github.com/urfave/cli/v2" "golang.org/x/term" ) func ActionUpload(c *cli.Context) error { - url := fmt.Sprintf("%s/api/file", c.String("url")) - client := &http.Client{} - // TODO: Change timeout - ctx, cancel := context.WithTimeout(c.Context, 10*time.Minute) - defer cancel() - - buf := &bytes.Buffer{} - mw := multipart.NewWriter(buf) - + clnt := client.Client{ + BaseURL: c.String("url"), + } for _, arg := range c.Args().Slice() { f, err := os.Open(arg) if err != nil { return err } defer f.Close() - fw, err := mw.CreateFormFile(uuid.Must(uuid.NewRandom()).String(), arg) + file := &files.File{ + OriginalFilename: arg, + Body: f, + } + resp, err := clnt.Upload(c.Context, file) if err != nil { - return err + errmsg := fmt.Sprintf("Error uploading file: %s", err) + return cli.Exit(errmsg, 1) } - if _, err := io.Copy(fw, f); err != nil { - return err - } - } - mw.Close() - req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, buf) - if err != nil { - return err - } - req.Header.Add("Content-Type", mw.FormDataContentType()) - - resp, err := client.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - - var expectedResp []struct { - Message string `json:"message"` - ID string `json:"id"` - URL string `json:"url"` - } - - decoder := json.NewDecoder(resp.Body) - if err := decoder.Decode(&expectedResp); err != nil { - return fmt.Errorf("error decoding response: %w", err) - } - - for _, r := range expectedResp { - fmt.Printf("Uploaded file %s\n", r.ID) + fmt.Printf("Uploaded file %s - %s", file.OriginalFilename, resp[0].URL) } return nil }