如何从Cloudflare获取视频ID或自定义ID上传视频(Golang)
Let’s work through your problem step by step—you’ve got two solid approaches to nail down that video ID, and we’ll adjust your existing code to make both work.
Approach 1: Let Cloudflare Generate the ID (Retrieve It Post-Upload)
Right now, your code uses Cloudflare’s tus endpoint, which automatically creates a unique ID for your video when you initiate the upload. The trick is pulling that ID from the uploader’s URL after calling CreateUpload.
Here’s how to tweak your code to grab the Cloudflare-assigned ID:
// ... [your existing code up to CreateUpload] uploader, err := client.CreateUpload(upload) if err != nil { log.Errorf("create upload error: %s", err) return c.JSONStatus(http.StatusInternalServerError) } // Extract the video ID from the uploader's URL import "strings" // Don't forget to add this import urlParts := strings.Split(uploader.URL, "/") videoID := urlParts[len(urlParts)-1] // Save this Cloudflare-generated ID to your database log.Printf("Cloudflare video ID: %s", videoID)
When you call CreateUpload, Cloudflare sends back a Location header (stored in uploader.URL by the tus client). The final segment of this URL is the unique ID Cloudflare assigned to your video.
Approach 2: Use a Custom-Generated ID (Your UUID)
Your earlier 400 error happened because you appended /id to the endpoint incorrectly—Cloudflare requires you to target a specific URL structure for custom IDs. To use your own UUID, you need to send a request to https://api.cloudflare.com/client/v4/accounts/{accountID}/media/{your-custom-id} using a PUT method (instead of the default POST for auto-generated IDs).
With the tus-go-client, you can use the CreateUploadAt method to target this custom URL. Here’s the adjusted code:
// ... [your existing code up to generating fileName] fileName := uuid.New().String() // Your custom UUID-based ID // Build the upload URL with your custom ID uploadURL := fmt.Sprintf("https://api.cloudflare.com/client/v4/accounts/%s/media/%s", accountID, fileName) // Create the uploader using your custom URL uploader, err := client.CreateUploadAt(upload, uploadURL) if err != nil { log.Errorf("create upload with custom ID error: %s", err) return c.JSONStatus(http.StatusInternalServerError) } // Your UUID (fileName) is now the video ID Cloudflare uses—save it to your DB log.Printf("Custom video ID in use: %s", fileName)
Key Notes for Custom IDs:
- Cloudflare requires custom IDs to only include alphanumeric characters, hyphens, and underscores, with a length between 1-64 characters. Your UUID fits this perfectly.
- If the custom ID is already used by another media item in your account, the request will fail—add retry logic if you want to handle duplicate IDs gracefully.
内容的提问来源于stack exchange,提问作者Klimbo

