Created
April 11, 2026 18:00
-
-
Save crgimenes/14246e3a4167d2d49260231e5621c1bf to your computer and use it in GitHub Desktop.
Upload file to Dropbox
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.") | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: