Skip to content

Instantly share code, notes, and snippets.

@crgimenes
Created April 11, 2026 18:00
Show Gist options
  • Select an option

  • Save crgimenes/14246e3a4167d2d49260231e5621c1bf to your computer and use it in GitHub Desktop.

Select an option

Save crgimenes/14246e3a4167d2d49260231e5621c1bf to your computer and use it in GitHub Desktop.
Upload file to Dropbox
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
type DropboxUploadArgs struct {
Path string `json:"path"`
Mode string `json:"mode"`
Autorename bool `json:"autorename"`
Mute bool `json:"mute"`
}
func uploadToDropbox(localPath, remotePath, token string) error {
file, err := os.Open(localPath)
if err != nil {
return fmt.Errorf("failed to open local file: %w", err)
}
defer file.Close()
args := DropboxUploadArgs{
Path: remotePath,
Mode: "overwrite",
Autorename: false,
Mute: false,
}
argJSON, err := json.Marshal(args)
if err != nil {
return fmt.Errorf("failed to marshal arguments: %w", err)
}
req, err := http.NewRequestWithContext(
context.Background(),
http.MethodPost,
"https://content.dropboxapi.com/2/files/upload",
file)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Dropbox-API-Arg", string(argJSON))
req.Header.Set("Content-Type", "application/octet-stream")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("request execution failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("api returned error (status %d): %s", resp.StatusCode, string(body))
}
return nil
}
func main() {
if len(os.Args) < 3 {
fmt.Printf("Usage: %s <local_file> <dropbox_path>\n", os.Args[0])
os.Exit(1)
}
localFile := os.Args[1]
remotePath := os.Args[2]
token, ok := os.LookupEnv("DROPBOX_ACCESS_TOKEN")
if !ok {
fmt.Fprintln(os.Stderr, "Error: DROPBOX_ACCESS_TOKEN environment variable not set")
os.Exit(1)
}
err := uploadToDropbox(localFile, remotePath, token)
if err != nil {
fmt.Fprintf(os.Stderr, "Upload failed: %v\n", err)
os.Exit(1)
}
fmt.Println("Upload completed successfully.")
}
@crgimenes

Copy link
Copy Markdown
Author

Example:

go run main.go file.zip /backup/file.zip

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment