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"
"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
}