utapi

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 6, 2025 License: Unlicense Imports: 7 Imported by: 0

README

utapi-go – UploadThing Go SDK

A Go client for interacting with UploadThing – supports file uploads, listing, deletion, and metadata operations.


📆 Installation

go get github.com/r0ld3x/utapi-go

🧠 Features

  • ✅ Upload files to UploadThing
  • 📄 List uploaded files
  • 🔄 Rename files
  • 🗑️ Delete files
  • 📆 Fetch file info
  • 🛡️ Typed API responses

⚙️ Usage

🔐 Initialize the client
  • Apikey format: sk_*************************
import "github.com/r0ld3x/utapi-go"

cfg := utapi.Config{
	ApiKey: "sk_*************************",
}
client := utapi.NewUtApi(cfg)

📁 Upload a File
fileInfo, err := utapi.GetFileInfo("example.pdf")
if err != nil {
	log.Fatal(err)
}

uploadOpts := utapi.PrepareUploadOpt{
	Files: []utapi.FileRequest{*fileInfo},
}

resp, err := client.PrepareUpload(uploadOpts)
if err != nil {
	log.Fatal(err)
}

err = client.UploadFile(&resp[0], "example.pdf")
if err != nil {
	log.Fatal(err)
}

📃 List Files
files, err := client.ListFiles(utapi.ListFilesOpts{})
if err != nil {
	log.Fatal(err)
}
fmt.Println("Files:", files)

✏️ Rename Files
renameOpts := utapi.RenameRequest{
	Updates: []utapi.RenameUpdate{
		{
			NewName: "renamed.pdf",
			FileKey: "your-file-key",
		},
	},
}

err := client.RenameFiles(renameOpts)
if err != nil {
	log.Fatal(err)
}

🗑️ Delete Files
deleteOpts := utapi.DeleteFilesOpt{
	FileKeys: []string{"your-file-key"},
}

err := client.DeleteFiles(deleteOpts)
if err != nil {
	log.Fatal(err)
}

📄 Documentation

Inline GoDocs are available at pkg.go.dev/github.com/r0ld3x/utapi-go Or run locally with:

godoc -http=:6060

🤝 Contributing

Pull requests and issues are welcome! Please ensure code is linted and tested.


📜 License

MIT © r0ld3x

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type DeleteFilesOpt

type DeleteFilesOpt struct {
	FileKeys []string `json:"fileKeys"`
}

type DeleteFilesResponse

type DeleteFilesResponse struct {
	Success      bool  `json:"success"`
	DeletedCount int64 `json:"deletedCount"`
}

type Fields

type Fields struct {
	ContentType        string `json:"Content-Type"`
	ContentDisposition string `json:"Content-Disposition"`
	Bucket             string `json:"bucket"`
	XAmzAlgorithm      string `json:"X-Amz-Algorithm"`
	XAmzCredential     string `json:"X-Amz-Credential"`
	XAmzDate           string `json:"X-Amz-Date"`
	XAmzSecurityToken  string `json:"X-Amz-Security-Token"`
	Key                string `json:"key"`
	Policy             string `json:"Policy"`
	XAmzSignature      string `json:"X-Amz-Signature"`
}

type File

type File struct {
	ID         string `json:"id"`
	Key        string `json:"key"`
	Name       string `json:"name"`
	Size       int64  `json:"size"`
	UploadedAt int64  `json:"uploadedAt"`
	CustomID   any    `json:"customId"`
	Status     string `json:"status"`
}

type FileRequest

type FileRequest struct {
	Name string `json:"name"`
	Size int64  `json:"size"`
	Type string `json:"type"`
}

func GetFileInfo

func GetFileInfo(filePath string) (*FileRequest, error)

type GetUsageInfoResponse

type GetUsageInfoResponse struct {
	TotalBytes    int64 `json:"totalBytes"`
	AppTotalBytes int64 `json:"appTotalBytes"`
	FilesUploaded int64 `json:"filesUploaded"`
	LimitBytes    int64 `json:"limitBytes"`
}

type ListFilesOpts

type ListFilesOpts struct {
	Limit  int64 `json:"limit"`
	Offset int64 `json:"offset"`
}

type ListFilesResponse

type ListFilesResponse struct {
	HasMore bool   `json:"hasMore"`
	Files   []File `json:"files"`
}

type PrepareUploadOpt

type PrepareUploadOpt struct {
	Files        []FileRequest `json:"files"`
	CallbackURL  string        `json:"callbackUrl"`
	CallbackSlug string        `json:"callbackSlug"`
	RouteConfig  []string      `json:"routeConfig"`
}

type PrepareUploadResponse

type PrepareUploadResponse struct {
	URL                string `json:"url"`
	Fields             Fields `json:"fields"`
	Key                string `json:"key"`
	ContentDisposition string `json:"contentDisposition"`
	FileURL            string `json:"fileUrl"`
	AppURL             string `json:"appUrl"`
	UfsURL             string `json:"ufsUrl"`
	PollingJwt         string `json:"pollingJwt"`
	PollingURL         string `json:"pollingUrl"`
	FileName           string `json:"fileName"`
	FileType           string `json:"fileType"`
	CustomID           any    `json:"customId"`
}

type RenameFilesOpt

type RenameFilesOpt struct {
	NewName string `json:"newName"`
	FileKey string `json:"fileKey"`
}

type RenameFilesOpts

type RenameFilesOpts []RenameFilesOpt

type RenameFilesResponse

type RenameFilesResponse struct {
	Success      bool  `json:"success"`
	RenamedCount int64 `json:"renamedCount"`
}

type RenameRequest

type RenameRequest struct {
	Updates RenameFilesOpts `json:"updates"`
}

type UtApi

type UtApi struct {
	// contains filtered or unexported fields
}

func NewUtApi

func NewUtApi(ApiKey string) *UtApi

NewUtApi - Create a new UtApi instance with the given API key.

Example: utapi := utapigo.NewUtApi("sk_...")

func (*UtApi) DeleteFiles

func (u *UtApi) DeleteFiles(opts DeleteFilesOpt) (*DeleteFilesResponse, error)

DeleteFiles deletes multiple files by their keys. Returns the number of files deleted.

Example:

deleteResponse, err := client.DeleteFiles(utapi.DeleteFilesOpt{
  FileKeys: []string{"file1", "file2", "file3"},
})
fmt.Println(deleteResponse.DeletedCount) // Output: 3

func (*UtApi) GetUsageInfo

func (u *UtApi) GetUsageInfo() (*GetUsageInfoResponse, error)

GetUsageInfo retrieves the total usage information for the user. Returns a pointer to a GetUsageInfoResponse object on success, or an error on failure.

Example:

usageInfo, err := utapi.GetUsageInfo()
if err != nil {
    fmt.Println("Error fetching usage info:", err.Error())
    return
}

func (*UtApi) ListFiles

func (u *UtApi) ListFiles(opts ListFilesOpts) (*ListFilesResponse, error)

ListFiles lists files in the user's storage. Example: -

listFiles, err := client.ListFiles(ut.ListFilesOpts{Limit: 10, Offset: 0})
if err != nil {
  fmt.Println("Error listing files:", err.Error())
  return
}
fmt.Printf("List of files (Limit: %d, Offset: %d):\n", listFiles.Limit, listFiles.Offset)

func (*UtApi) MakeRequest

func (u *UtApi) MakeRequest(apiEndpoint string, method string, body *bytes.Buffer) (*http.Response, error)

MakeRequest - Make a request to the uploadthing API. Returns the response and an error if any occurred. The error will be nil if the request was successful. If the request fails, the error will contain an error message. The response body will be read and closed automatically. The response will contain the HTTP status code. If the status code is not 200, the error message will include the response body.

func (*UtApi) PrepareUpload

func (u *UtApi) PrepareUpload(opts PrepareUploadOpt) (*PrepareUploadResponse, error)

PrepareUpload retrieves the data to upload file Returns the URL to upload the file, fields for the POST request, and the key for the file If there's an error, it returns an error message.

Example:

prepareUpload, err := client.PrepareUpload(utapi.PrepareUploadOpt{
  Files: []utapi.FileRequest{{Name: "file.txt", Size: 1024, Type: "text/plain"}},
  CallbackURL:  "http://example.com/callback",
  CallbackSlug: "file.txt",
  RouteConfig:  []string{"text"},
})
if err != nil {
  fmt.Println("Error preparing upload:", err.Error())
  return
}

func (*UtApi) RenameFiles

func (u *UtApi) RenameFiles(opts RenameFilesOpts) (*RenameFilesResponse, error)

RenameFiles renames files in a user's cloud storage. Returns a RenameFilesResponse containing a boolean indicating success and the count of renamed files.

Example:

 opts := []RenameFilesOpt{
   {NewName: "new_name.txt", FileKey: "old_key.txt"},
 }
 result, err := client.RenameFiles(opts)
 if err != nil {
   panic(err)
}

func (*UtApi) UploadFile

func (u *UtApi) UploadFile(responseItem *PrepareUploadResponse, filePath string) error

UploadFile uploads a file to the UploadThing server.

This function takes a file path from the local filesystem and uploads the file to the server using the information provided in the PrepareUploadResponse.

Example:

resp, _ := ut.PrepareUpload(...)
err := ut.UploadFile(&resp, "example.pdf")
if err != nil {
    log.Fatal(err)
}

Parameters:

  • responseItem: A pointer to the PrepareUploadResponse object returned from the PrepareUpload API.
  • filePath: The full path to the local file you want to upload.

Returns an error if the upload fails or the file cannot be read.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL