Use client for upload action

This commit is contained in:
Torjus Håkestad 2022-01-20 23:17:09 +01:00
parent 733c0410fe
commit 193b0d3926

View File

@ -5,8 +5,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io"
"mime/multipart"
"net/http" "net/http"
"os" "os"
"strings" "strings"
@ -14,61 +12,32 @@ import (
"time" "time"
"git.t-juice.club/torjus/gpaste/api" "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" "github.com/urfave/cli/v2"
"golang.org/x/term" "golang.org/x/term"
) )
func ActionUpload(c *cli.Context) error { func ActionUpload(c *cli.Context) error {
url := fmt.Sprintf("%s/api/file", c.String("url")) clnt := client.Client{
client := &http.Client{} BaseURL: c.String("url"),
// TODO: Change timeout }
ctx, cancel := context.WithTimeout(c.Context, 10*time.Minute)
defer cancel()
buf := &bytes.Buffer{}
mw := multipart.NewWriter(buf)
for _, arg := range c.Args().Slice() { for _, arg := range c.Args().Slice() {
f, err := os.Open(arg) f, err := os.Open(arg)
if err != nil { if err != nil {
return err return err
} }
defer f.Close() 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 { 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 { fmt.Printf("Uploaded file %s - %s", file.OriginalFilename, resp[0].URL)
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)
} }
return nil return nil
} }