Skip to content

Commit

Permalink
refactor: Simplify transfer.sh file interaction
Browse files Browse the repository at this point in the history
  • Loading branch information
WillFantom committed Jan 23, 2023
1 parent f10d34e commit bbfdf02
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
38 changes: 38 additions & 0 deletions internal/transfer/file.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,26 @@
package transfer

import (
"net/http"
"net/url"

"fmt"
)

// TransferShFile is information pertaining to a file uploaded to transfer.sh,
// including the download URL and the deletion token.
type TransferShFile struct {
downloadURL string
deleteToken string
}

func NewFile(downloadURL, deleteToken string) *TransferShFile {
return &TransferShFile{
downloadURL: downloadURL,
deleteToken: deleteToken,
}
}

// DownloadURL is the full URL that can be used to download the contents of a
// file uploaded to the https://transfer.sh file store.
func (tshFile TransferShFile) DownloadURL() string {
Expand All @@ -18,3 +32,27 @@ func (tshFile TransferShFile) DownloadURL() string {
func (tshFile TransferShFile) DeleteToken() string {
return tshFile.deleteToken
}

// Delete attempts to delete the file from transfer.sh using the file's download
// link and delete token. If an error is returned this may indicate that the
// file has already been deleted or that the request to delete was simply not
// successful.
func (tshFile TransferShFile) Delete() error {
deleteURL, err := url.JoinPath(tshFile.downloadURL, tshFile.deleteToken)
if err != nil {
return fmt.Errorf("failed to generate valid url for transfer.sh file delete")
}
req, err := http.NewRequest(http.MethodDelete, deleteURL, nil)
if err != nil {
return fmt.Errorf("failed to generate file delete request: %w", err)
}
resp, err := (&http.Client{}).Do(req)
if err != nil {
return fmt.Errorf("failed to perform the delete request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("failed to delete file from transfer.sh: %w", err)
}
return nil
}
5 changes: 1 addition & 4 deletions internal/transfer/upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,5 @@ func (tsh TransferSh) Upload(data string) (*TransferShFile, error) {
if deleteURL == "" || downloadURL == "" {
return nil, fmt.Errorf("failed to obtain all urls for the transfer.sh upload")
}
return &TransferShFile{
downloadURL: downloadURL,
deleteToken: path.Base(deleteURL),
}, nil
return NewFile(downloadURL, path.Base(deleteURL)), nil
}

0 comments on commit bbfdf02

Please sign in to comment.