=============== LIBRARY RULES =============== From library maintainers: - 模块路径为 github.com/qiniu/go-sdk/v7,import 时必须带 /v7 后缀 - 新项目推荐使用 storagev2 包(v2 API),而非 storage 包(v1 API) - 认证凭证通过 auth.New(accessKey, secretKey) 创建,AK/SK 从 https://portal.qiniu.com/user/key 获取 - storagev2 体系使用 Provider 接口模式:CredentialsProvider、RegionsProvider、UpTokenProvider - 上传使用 storagev2/uploader.NewUploadManager,会根据文件大小自动选择表单上传或分片上传 - 下载使用 storagev2/downloader.NewDownloadManager,支持并发分片下载 - 对象管理使用 storagev2/objects.NewObjectsManager,支持链式 API:Bucket(name).Object(key).Stat().Call(ctx) - 上传凭证通过 storagev2/uptoken.NewPutPolicy 创建策略,uptoken.NewSigner 生成签名 - storagev2 子包的 Options 结构体通常嵌入 http_client.Options,其中 Credentials 字段传递凭证 - storage(v1)包使用 Manager 模式:BucketManager、FormUploader、ResumeUploaderV2 - CDN 使用 cdn.NewCdnManager(mac),直播使用 pili.NewManager(mac) - 短信使用 sms.NewManager(mac),视频监控使用 qvs.NewManager(mac, nil) - 实时音视频使用 rtc.NewManager(mac),IoT 设备联网使用 linking.NewManager(mac) - 沙箱服务使用 sandbox 包,通过 sandbox.NewClient 创建客户端,管理沙箱生命周期、文件操作和命令执行 - IAM 使用 iam/apis.NewIam(&http_client.Options{Credentials: cred}),管理子账号、用户组和策略 - 多媒体处理使用 media/apis.NewMedia(&http_client.Options{Credentials: cred}),触发和查询持久化数据处理 - 审计日志使用 audit/apis.NewAudit(&http_client.Options{Credentials: cred}),查询账号操作审计日志 - storagev2/apis 和 iam/apis 等带 DO NOT EDIT DIRECTLY 注释的文件为自动生成代码,不要手动修改 ### Installation Source: https://context7.com/qiniu/go-sdk/llms.txt Instructions for installing the Qiniu Go SDK v7 using go get and updating go.mod. ```APIDOC ## Installation ```bash go get github.com/qiniu/go-sdk/v7 ``` In `go.mod`: ``` require github.com/qiniu/go-sdk/v7 v7.26.10 ``` ``` -------------------------------- ### Install Qiniu Go SDK Source: https://github.com/qiniu/go-sdk/blob/master/README.md Use `go get` to install the latest version of the SDK. Ensure your Go version is 1.22 or higher. ```bash go get github.com/qiniu/go-sdk/v7 ``` -------------------------------- ### Quick Start: Upload File with Qiniu Go SDK Source: https://github.com/qiniu/go-sdk/blob/master/README.md This example demonstrates how to upload a file to Qiniu Object Storage using the SDK. Obtain your Access Key and Secret Key from the Qiniu portal. Ensure you have a bucket created. ```go package main import ( "context" "fmt" "time" "github.com/qiniu/go-sdk/v7/storagev2/credentials" "github.com/qiniu/go-sdk/v7/storagev2/http_client" "github.com/qiniu/go-sdk/v7/storagev2/uploader" "github.com/qiniu/go-sdk/v7/storagev2/uptoken" ) func main() { // 创建凭证(AK/SK 从 https://portal.qiniu.com/user/key 获取) cred := credentials.NewCredentials("AccessKey", "SecretKey") // 创建上传策略和凭证 putPolicy, _ := uptoken.NewPutPolicy("my-bucket", time.Now().Add(time.Hour)) // 创建上传管理器 uploadManager := uploader.NewUploadManager(&uploader.UploadManagerOptions{ Options: http_client.Options{Credentials: cred}, }) // 上传文件 objectName := "my-file.txt" err := uploadManager.UploadFile(context.Background(), "/path/to/file", &uploader.ObjectOptions{ BucketName: "my-bucket", ObjectName: &objectName, UpToken: uptoken.NewSigner(putPolicy, cred), }, nil) if err != nil { fmt.Println("上传失败:", err) return } fmt.Println("上传成功") } ``` -------------------------------- ### Install Qiniu Go SDK v7 Source: https://context7.com/qiniu/go-sdk/llms.txt Install the Qiniu Go SDK v7 using go get. Ensure your Go version is 1.22 or higher. ```bash go get github.com/qiniu/go-sdk/v7 ``` ```go.mod require github.com/qiniu/go-sdk/v7 v7.26.10 ``` -------------------------------- ### Create and Use Sandbox Source: https://github.com/qiniu/go-sdk/blob/master/llms.txt Example demonstrating how to create and interact with a Qiniu sandbox environment. Sandboxes are useful for isolated execution of commands or file operations. ```go package main import ( "fmt" "github.com/qiniu/go-sdk/v7/auth" "github.com/qiniu/go-sdk/v7/sandbox" ) func main() { // Replace with your actual Access Key and Secret Key accessKey := "your_access_key" secretKey := "your_secret_key" // Create authentication credentials authCredentials := auth.New(accessKey, secretKey) // Create a sandbox client ssandboxClient, err := sandbox.NewClient(authCredentials) if err != nil { fmt.Printf("Error creating sandbox client: %v\n", err) return } // Create a new sandbox ssandboxID, err := sandboxClient.CreateSandbox(nil) // nil for default options if err != nil { fmt.Printf("Error creating sandbox: %v\n", err) return } fmt.Printf("Sandbox created with ID: %s\n", sandboxID) // Example: Execute a command in the sandbox command := "ls -l /" output, err := sandboxClient.ExecuteCommand(sandboxID, command, nil) // nil for default options if err != nil { fmt.Printf("Error executing command: %v\n", err) // Clean up the sandbox even if command execution fails _ = sandboxClient.DeleteSandbox(sandboxID) return } fmt.Printf("Command output:\n%s\n", output) // Clean up the sandbox when done err = sandboxClient.DeleteSandbox(sandboxID) if err != nil { fmt.Printf("Error deleting sandbox: %v\n", err) return } fmt.Printf("Sandbox %s deleted successfully.\n", sandboxID) } ``` -------------------------------- ### Get File Information Source: https://github.com/qiniu/go-sdk/blob/master/llms.txt Example for retrieving metadata of a file in a Qiniu bucket using the `Stat` method. This is useful for checking file existence, size, and other properties. ```go package main import ( "context" "fmt" "github.com/qiniu/go-sdk/v7/auth" "github.com/qiniu/go-sdk/v7/storage" ) func main() { // Replace with your actual Access Key and Secret Key accessKey := "your_access_key" secretKey := "your_secret_key" // Replace with your bucket name bucketName := "your_bucket_name" // Replace with the key of the file you want to stat key := "your_file_key.txt" // Create authentication credentials authCredentials := auth.New(accessKey, secretKey) // Create a storage manager bucketManager := storage.NewBucketManager(authCredentials, nil) // Get file information fileInfo, err := bucketManager.Stat(bucketName, key) if err != nil { fmt.Printf("Error getting file info: %v\n", err) return } fmt.Printf("File Info: %+v\n", fileInfo) } ``` -------------------------------- ### Initialize API Specs Submodule Source: https://github.com/qiniu/go-sdk/blob/master/AGENTS.md Before starting development, initialize the api-specs submodule to ensure all API specifications are available. ```bash # 初始化 api-specs submodule git submodule update --init --recursive ``` -------------------------------- ### Simple Form Upload Source: https://github.com/qiniu/go-sdk/blob/master/llms.txt Example demonstrating how to perform a simple form upload for small files using the Qiniu Go SDK. Ensure you have the necessary authentication credentials. ```go package main import ( "context" "fmt" "github.com/qiniu/go-sdk/v7/auth" "github.com/qiniu/go-sdk/v7/storage" ) func main() { // Replace with your actual Access Key and Secret Key accessKey := "your_access_key" secretKey := "your_secret_key" // Replace with your bucket name bucketName := "your_bucket_name" // Replace with the path to your local file filePath := "path/to/your/local/file.txt" // Replace with the desired key for the uploaded file in the bucket key := "your_file_key.txt" // Create authentication credentials authCredentials := auth.New(accessKey, secretKey) // Create a storage manager bucketManager := storage.NewBucketManager(authCredentials, nil) // Upload the file uploadResult, err := bucketManager.UploadFile(context.Background(), bucketName, key, filePath, nil) if err != nil { fmt.Printf("Error uploading file: %v\n", err) return } fmt.Printf("File uploaded successfully. Etag: %s\n", uploadiResult.Etag) } ``` -------------------------------- ### Move File Source: https://github.com/qiniu/go-sdk/blob/master/llms.txt Example for moving a file within the same or a different bucket using the `Move` method. This is equivalent to a copy followed by a delete. ```go package main import ( "context" "fmt" "github.com/qiniu/go-sdk/v7/auth" "github.com/qiniu/go-sdk/v7/storage" ) func main() { // Replace with your actual Access Key and Secret Key accessKey := "your_access_key" secretKey := "your_secret_key" // Replace with your source bucket name sourceBucketName := "your_source_bucket" // Replace with the key of the source file sourceKey := "path/to/source/file_to_move.txt" // Replace with your destination bucket name (can be the same as source) destinationBucketName := "your_destination_bucket" // Replace with the desired key for the moved file destinationKey := "path/to/destination/moved_file.txt" // Create authentication credentials authCredentials := auth.New(accessKey, secretKey) // Create a storage manager bucketManager := storage.NewBucketManager(authCredentials, nil) // Move the file moveResult, err := bucketManager.Move( sourceBucketName, sourceKey, destinationBucketName, destinationKey, false, // Force overwrite if true ) if err != nil { fmt.Printf("Error moving file: %v\n", err) return } fmt.Printf("File moved successfully. New Etag: %s\n", moveResult.Etag) } ``` -------------------------------- ### Copy File Source: https://github.com/qiniu/go-sdk/blob/master/llms.txt Example for copying a file within the same or a different bucket using the `Copy` method. This operation requires appropriate permissions. ```go package main import ( "context" "fmt" "github.com/qiniu/go-sdk/v7/auth" "github.com/qiniu/go-sdk/v7/storage" ) func main() { // Replace with your actual Access Key and Secret Key accessKey := "your_access_key" secretKey := "your_secret_key" // Replace with your source bucket name sourceBucketName := "your_source_bucket" // Replace with the key of the source file sourceKey := "path/to/source/file.txt" // Replace with your destination bucket name (can be the same as source) destinationBucketName := "your_destination_bucket" // Replace with the desired key for the copied file destinationKey := "path/to/destination/copied_file.txt" // Create authentication credentials authCredentials := auth.New(accessKey, secretKey) // Create a storage manager bucketManager := storage.NewBucketManager(authCredentials, nil) // Copy the file copyResult, err := bucketManager.Copy( sourceBucketName, sourceKey, destinationBucketName, destinationKey, false, // Force overwrite if true ) if err != nil { fmt.Printf("Error copying file: %v\n", err) return } fmt.Printf("File copied successfully. New Etag: %s\n", copyResult.Etag) } ``` -------------------------------- ### Delete File Source: https://github.com/qiniu/go-sdk/blob/master/llms.txt Example for deleting a file from a Qiniu bucket using the `Delete` method. Ensure you have the necessary permissions to delete objects. ```go package main import ( "context" "fmt" "github.com/qiniu/go-sdk/v7/auth" "github.com/qiniu/go-sdk/v7/storage" ) func main() { // Replace with your actual Access Key and Secret Key accessKey := "your_access_key" secretKey := "your_secret_key" // Replace with your bucket name bucketName := "your_bucket_name" // Replace with the key of the file to delete key := "path/to/file_to_delete.txt" // Create authentication credentials authCredentials := auth.New(accessKey, secretKey) // Create a storage manager bucketManager := storage.NewBucketManager(authCredentials, nil) // Delete the file err := bucketManager.Delete(bucketName, key) if err != nil { fmt.Printf("Error deleting file: %v\n", err) return } fmt.Printf("File deleted successfully.") } ``` -------------------------------- ### Simple Resume Upload Source: https://github.com/qiniu/go-sdk/blob/master/llms.txt Example for uploading large files using the resume upload mechanism. This method is suitable for large files as it supports resuming interrupted uploads. ```go package main import ( "context" "fmt" "os" "github.com/qiniu/go-sdk/v7/auth" "github.com/qiniu/go-sdk/v7/storage" ) func main() { // Replace with your actual Access Key and Secret Key accessKey := "your_access_key" secretKey := "your_secret_key" // Replace with your bucket name bucketName := "your_bucket_name" // Replace with the path to your local file filePath := "path/to/your/large/file.zip" // Replace with the desired key for the uploaded file in the bucket key := "your_large_file_key.zip" // Create authentication credentials authCredentials := auth.New(accessKey, secretKey) // Create a storage manager bucketManager := storage.NewBucketManager(authCredentials, nil) // Open the file to upload file, err := os.Open(filePath) if err != nil { fmt.Printf("Error opening file: %v\n", err) return } defer file.Close() // Get file size fileInfo, err := file.Stat() if err != nil { fmt.Printf("Error getting file info: %v\n", err) return } fileSize := fileInfo.Size() // Upload the file using resume upload uploadResult, err := bucketManager.Upload( context.Background(), bucketName, key, file, fileSize, "application/octet-stream", // Content type, adjust as needed nil, // Optional upload options ) if err != nil { fmt.Printf("Error uploading file: %v\n", err) return } fmt.Printf("File uploaded successfully. Etag: %s\n", uploadiResult.Etag) } ``` -------------------------------- ### CDN URL/Directory Refresh Source: https://github.com/qiniu/go-sdk/blob/master/llms.txt Example for refreshing CDN cached content for specified URLs or directories. This forces Qiniu CDN to re-fetch the latest content from the origin. ```go package main import ( "fmt" "github.com/qiniu/go-sdk/v7/auth" "github.com/qiniu/go-sdk/v7/cdn" ) func main() { // Replace with your actual Access Key and Secret Key accessKey := "your_access_key" secretKey := "your_secret_key" // Create authentication credentials authCredentials := auth.New(accessKey, secretKey) // Create a CDN manager cdnManager := cdn.NewManager(authCredentials) // URLs to refresh urlsToRefresh := []string{ "http://your.domain.com/path/to/file.jpg", "http://your.domain.com/another/path/", } // Refresh URLs refreshResult, err := cdnManager.RefreshUrls(urlsToRefresh) if err != nil { fmt.Printf("Error refreshing URLs: %v\n", err) return } fmt.Printf("URL Refresh Task ID: %s\n", refreshResult.TaskID) // Directories to refresh (use with caution, can consume quota) dirsToRefresh := []string{ "your.domain.com/some/directory/", } // Refresh directories dirRefreshResult, err := cdnManager.RefreshDirs(dirsToRefresh) if err != nil { fmt.Printf("Error refreshing directories: %v\n", err) return } fmt.Printf("Directory Refresh Task ID: %s\n", dirRefreshResult.TaskID) } ``` -------------------------------- ### Interceptor Chain Example Source: https://github.com/qiniu/go-sdk/blob/master/AGENTS.md Illustrates the typical order of interceptors in the SDK's HTTP client v2. Interceptors are prioritized by a numerical value, with lower numbers indicating higher priority. This chain handles retries, logging, authentication, and other request/response modifications. ```go RetryHosts(200) → RetrySimple(300) → Uplog(310) → BufferResponse(320) → SetHeader(400) → Normal(500) → Auth(600) → AntiHijacking(700) → Debug(800) ``` -------------------------------- ### Sandbox Code Generation Command Source: https://github.com/qiniu/go-sdk/blob/master/AGENTS.md Command to generate code for the sandbox environment, which uses a different toolchain including OpenAPI and Protocol Buffers. This requires specific tools like `buf` and `protoc-gen-go` to be installed. ```bash make generate-sandbox # 需要安装 buf、protoc-gen-go、protoc-gen-connect-go ``` -------------------------------- ### Create and Manage Sandbox Environment in Go Source: https://context7.com/qiniu/go-sdk/llms.txt Demonstrates creating a sandbox client, creating and waiting for a sandbox to be ready, executing commands, performing file system operations, and pausing the sandbox. Ensure QINIU_API_KEY is set in your environment. ```go package main import ( "context" "fmt" "os" "time" "github.com/qiniu/go-sdk/v7/sandbox" ) func main() { c, err := sandbox.NewClient(&sandbox.Config{ APIKey: os.Getenv("QINIU_API_KEY"), }) if err != nil { panic(err) } ctx := context.Background() timeout := int32(120) // 创建沙箱并等待就绪 sb, _, err := c.CreateAndWait(ctx, sandbox.CreateParams{ TemplateID: "base", Timeout: &timeout, }, sandbox.WithPollInterval(2*time.Second)) if err != nil { panic(err) } defer sb.Kill(ctx) fmt.Println("沙箱已就绪:", sb.ID()) // 执行命令(同步) result, err := sb.Commands().Run(ctx, "python3 -c \"print('hello from sandbox')\"", sandbox.WithEnvs(map[string]string{"MY_VAR": "hello"}), sandbox.WithCwd("/tmp"), sandbox.WithTimeout(10*time.Second), ) if err != nil { fmt.Fprintln(os.Stderr, "命令执行失败:", err) return } fmt.Printf("stdout: %s\nexitCode: %d\n", result.Stdout, result.ExitCode) // 文件系统操作 fs := sb.Files() fs.Write(ctx, "/tmp/hello.py", []byte("print('Hello from file!')")) content, err := fs.Read(ctx, "/tmp/hello.py") if err == nil { fmt.Println("文件内容:", string(content)) } // 列出目录 entries, _ := fs.List(ctx, "/tmp") for _, e := range entries { fmt.Printf(" %s (%d bytes)\n", e.Name, e.Size) } // 暂停沙箱(保留状态,可恢复) if err := sb.Pause(ctx); err != nil { fmt.Fprintln(os.Stderr, "暂停失败:", err) } else { fmt.Println("沙箱已暂停") } } ``` -------------------------------- ### Sign Data and HTTP Requests with Qiniu Auth in Go Source: https://context7.com/qiniu/go-sdk/llms.txt Shows how to create an authentication client, sign raw data for private URLs, add Qiniu authorization headers to HTTP requests, and generate management credentials. Replace 'your-access-key' and 'your-secret-key' with your actual credentials. ```go package main import ( "fmt" "net/http" "time" "github.com/qiniu/go-sdk/v7/auth" ) func main() { mac := auth.New("your-access-key", "your-secret-key") // 签名原始数据(私有下载 URL 用途) dataToSign := []byte("https://example.com/private/file.jpg?e=1893456000") token := mac.Sign(dataToSign) fmt.Println("Token:", token) // 对 HTTP 请求添加 Qiniu 鉴权头 req, _ := http.NewRequest("GET", "https://rs.qiniu.com/stat/bXktYnVja2V0OmhlbGxvLnR4dA==", nil) mac.AddToken(auth.TokenQiniu, req) fmt.Println("Authorization:", req.Header.Get("Authorization")) // 生成管理凭证(用于 BucketManager 等 v1 接口) accessToken, err := mac.SignRequest(req) if err != nil { fmt.Println("SignRequest 失败:", err) return } fmt.Println("管理凭证:", accessToken) // 下载 URL 签名(私有空间) deadline := time.Now().Add(time.Hour).Unix() rawURL := "https://example.com/private/photo.jpg" downloadToken := mac.Sign([]byte(fmt.Sprintf("%s?e=%d", rawURL, deadline))) fmt.Printf("私有下载地址: %s?e=%d&token=%s\n", rawURL, deadline, downloadToken) } ``` -------------------------------- ### Manage Credentials with storagev2/credentials Source: https://context7.com/qiniu/go-sdk/llms.txt Demonstrates how to create and manage Qiniu credentials using AK/SK, environment variables, or chained providers for API authentication. ```go package main import ( "context" "fmt" "os" "github.com/qiniu/go-sdk/v7/storagev2/credentials" ) func main() { // 方式 1:直接构建 cred := credentials.NewCredentials("your-access-key", "your-secret-key") fmt.Println("AK:", cred.AccessKey) // 方式 2:从环境变量读取 // export QINIU_ACCESS_KEY=xxx QINIU_SECRET_KEY=yyy envProvider := &credentials.EnvironmentVariableCredentialProvider{} cred2, err := envProvider.Get(context.Background()) if err != nil { fmt.Fprintln(os.Stderr, "环境变量未设置:", err) return } fmt.Println("AK from env:", cred2.AccessKey) // 方式 3:链式 Provider(依次尝试) chain := &credentials.ChainedCredentialsProvider{} _ = chain } ``` -------------------------------- ### Sandbox Service Client Source: https://context7.com/qiniu/go-sdk/llms.txt Demonstrates how to create a sandbox client, manage its lifecycle, execute commands, and perform file system operations. ```APIDOC ## Sandbox Service (`sandbox`) `sandbox.Client` provides a secure, isolated cloud code execution environment. It supports sandbox lifecycle management, command execution, file system operations, PTY terminal, and template management, designed for AI Agent scenarios with startup latency under 200ms. ### Create and Wait for Sandbox ```go // Create a new sandbox client c, err := sandbox.NewClient(&sandbox.Config{ APIKey: os.Getenv("QINIU_API_KEY"), }) if err != nil { panic(err) } ctx := context.Background() timeout := int32(120) // Create a sandbox and wait until it's ready sb, _, err := c.CreateAndWait(ctx, sandbox.CreateParams{ TemplateID: "base", Timeout: &timeout, }, sandbox.WithPollInterval(2*time.Second)) if err != nil { panic(err) } // Ensure the sandbox is killed when done defer sb.Kill(ctx) fmt.Println("Sandbox ready:", sb.ID()) ``` ### Execute Commands (Synchronous) ```go // Execute a command within the sandbox result, err := sb.Commands().Run(ctx, "python3 -c \"print('hello from sandbox')\"", sandbox.WithEnvs(map[string]string{"MY_VAR": "hello"}), sandbox.WithCwd("/tmp"), sandbox.WithTimeout(10*time.Second), ) if err != nil { fmt.Fprintln(os.Stderr, "Command execution failed:", err) return } fmt.Printf("stdout: %s\nexitCode: %d\n", result.Stdout, result.ExitCode) ``` ### File System Operations ```go fs := sb.Files() // Write a file to the sandbox fs.Write(ctx, "/tmp/hello.py", []byte("print('Hello from file!')")) // Read a file from the sandbox content, err := fs.Read(ctx, "/tmp/hello.py") if err == nil { fmt.Println("File content:", string(content)) } // List directory entries entries, _ := fs.List(ctx, "/tmp") for _, e := range entries { fmt.Printf(" %s (%d bytes)\n", e.Name, e.Size) } ``` ### Pause Sandbox ```go // Pause the sandbox (preserves state, can be resumed) if err := sb.Pause(ctx); err != nil { fmt.Fprintln(os.Stderr, "Pause failed:", err) } else { fmt.Println("Sandbox paused") } ``` ``` -------------------------------- ### Credentials Management (storagev2/credentials) Source: https://context7.com/qiniu/go-sdk/llms.txt Demonstrates how to create and manage credentials for API authentication using different methods: direct AK/SK, environment variables, and chained providers. ```APIDOC ## Credentials Management (`storagev2/credentials`) Build `Credentials` objects for all API authentications. Supports direct AK/SK input, reading from environment variables (`QINIU_ACCESS_KEY` / `QINIU_SECRET_KEY`), and chained providers. ```go package main import ( "context" "fmt" "os" "github.com/qiniu/go-sdk/v7/storagev2/credentials" ) func main() { // Method 1: Direct construction cred := credentials.NewCredentials("your-access-key", "your-secret-key") fmt.Println("AK:", cred.AccessKey) // Method 2: Read from environment variables // export QINIU_ACCESS_KEY=xxx QINIU_SECRET_KEY=yyy envProvider := &credentials.EnvironmentVariableCredentialProvider{} cred2, err := envProvider.Get(context.Background()) if err != nil { fmt.Fprintln(os.Stderr, "Environment variables not set:", err) return } fmt.Println("AK from env:", cred2.AccessKey) // Method 3: Chained Provider (try in order) chain := &credentials.ChainedCredentialsProvider{} _ = chain } ``` ``` -------------------------------- ### Add Qiniu Go SDK to go.mod Source: https://github.com/qiniu/go-sdk/blob/master/README.md Specify the SDK version in your `go.mod` file for dependency management. ```go require github.com/qiniu/go-sdk/v7 v7.26.10 ``` -------------------------------- ### Create Auth Credentials Source: https://github.com/qiniu/go-sdk/blob/master/llms.txt Use `auth.New` to create authentication credentials with your Access Key and Secret Key. This is required for most Qiniu API operations. ```go import "github.com/qiniu/go-sdk/v7/auth" func main() { accessKey := "your_access_key" secretKey := "your_secret_key" // Create authentication credentials authCredentials := auth.New(accessKey, secretKey) _ = authCredentials // Use authCredentials for API calls } ``` -------------------------------- ### Manage IAM Users with Go SDK Source: https://context7.com/qiniu/go-sdk/llms.txt Use iam/apis.NewIam to create a client for managing sub-accounts, user groups, and permission policies. Requires valid credentials. ```go package main import ( "context" "fmt" "github.com/qiniu/go-sdk/v7/iam/apis" iamreqs "github.com/qiniu/go-sdk/v7/iam/apis/create_user" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" "github.com/qiniu/go-sdk/v7/storagev2/credentials" ) func main() { cred := credentials.NewCredentials("your-access-key", "your-secret-key") iamClient := apis.NewIam(&httpclient.Options{Credentials: cred}) ctx := context.Background() // 创建子账号 user, err := iamClient.CreateUser(ctx, &iamreqs.Request{ Alias: "dev-alice", Password: "P@ssw0rd!", }, nil) if err != nil { fmt.Println("创建用户失败:", err) return } fmt.Printf("子账号 ID: %s\n", user.Data.ID) // 查询用户列表 users, err := iamClient.GetUsers(ctx, nil, nil) if err != nil { fmt.Println("查询用户失败:", err) return } for _, u := range users.Data.List { fmt.Printf("用户: %s (别名: %s)\n", u.ID, u.Alias) } } ``` -------------------------------- ### Upload Token and Policy (storagev2/uptoken) Source: https://context7.com/qiniu/go-sdk/llms.txt Explains how to define upload policies using `PutPolicy` (bucket, expiration, callbacks, size limits) and generate upload tokens using `NewSigner`. ```APIDOC ## Upload Token and Policy (`storagev2/uptoken`) `PutPolicy` defines the upload policy (storage bucket, expiration time, callbacks, size limits, etc.), and `NewSigner` combines the policy with credentials to generate an upload token. ```go package main import ( "fmt" "time" "github.com/qiniu/go-sdk/v7/storagev2/credentials" "github.com/qiniu/go-sdk/v7/storagev2/uptoken" ) func main() { cred := credentials.NewCredentials("your-access-key", "your-secret-key") // Upload policy for the entire bucket, valid for 1 hour policy, err := uptoken.NewPutPolicy("my-bucket", time.Now().Add(time.Hour)) if err != nil { panic(err) } // Upload policy for a specific object policyWithKey, err := uptoken.NewPutPolicyWithKey("my-bucket", "photos/avatar.jpg", time.Now().Add(time.Hour)) if err != nil { panic(err) } // Set callback policyWithKey.SetCallbackURL("https://example.com/callback", "example.com"). SetCallbackBody(`{"key":"$(key)","size":$(fsize)}`, "application/json") // Generate upload token string (for client SDK or form upload) signer := uptoken.NewSigner(policy, cred) token, err := signer.GetUpToken(nil) if err != nil { panic(err) } fmt.Println("UpToken:", token) _ = policyWithKey } ``` ``` -------------------------------- ### Download Files with Go SDK Source: https://context7.com/qiniu/go-sdk/llms.txt Use `DownloadManager` to download objects to a file or `io.Writer`. Supports automatic generation of private download URLs via `CredentialsSigner` and concurrent chunked downloads for large files. Ensure necessary credentials and bucket information are configured. ```go package main import ( "context" "fmt" "os" "github.com/qiniu/go-sdk/v7/storagev2/credentials" "github.com/qiniu/go-sdk/v7/storagev2/downloader" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" "github.com/qiniu/go-sdk/v7/storagev2/region" ) func main() { cred := credentials.NewCredentials("your-access-key", "your-secret-key") // 构造私有空间下载 URL 生成器 urlsProvider := downloader.NewPublicBucketURLsProvider( "my-bucket", region.HuaDong, // 区域,自动或指定 &downloader.GenerateOptions{UseInsecureProtocol: false}, ) // 私有空间需要签名 signedProvider := downloader.NewSignedURLsProvider( urlsProvider, downloader.NewCredentialsSigner(cred), nil, ) manager := downloader.NewDownloadManager(&downloader.DownloadManagerOptions{ Options: httpclient.Options{Credentials: cred}, DownloadURLsProvider: signedProvider, }) ctx := context.Background() // 下载到文件 size, err := manager.DownloadToFile(ctx, "docs/readme.txt", "/tmp/readme_dl.txt", nil) if err != nil { fmt.Fprintln(os.Stderr, "下载失败:", err) return } fmt.Printf("下载完成,大小: %d bytes\n", size) // 下载到 io.Writer(标准输出) size, err = manager.DownloadToWriter(ctx, "hello.txt", os.Stdout, nil) if err != nil { fmt.Fprintln(os.Stderr, "下载失败:", err) return } fmt.Printf("\n下载完成,大小: %d bytes\n", size) } ``` -------------------------------- ### Manage Live Streaming Services with Go SDK Source: https://context7.com/qiniu/go-sdk/llms.txt Utilize pili.Manager for managing live streaming hubs and streams, generating push and play URLs with signature calculations, and retrieving statistics. ```go package main import ( "fmt" "github.com/qiniu/go-sdk/v7/pili" ) func main() { conf := pili.ManagerConfig{ AccessKey: "your-access-key", SecretKey: "your-secret-key", } manager := pili.NewManager(conf) // 查询直播空间信息 hub, err := manager.GetHub("my-hub") if err != nil { fmt.Println("获取 Hub 失败:", err) } else { fmt.Printf("Hub: %+v\n", hub) } // 查询直播流列表 resp, err := manager.GetStreams(pili.GetStreamsRequest{Hub: "my-hub", LiveOnly: false}) if err != nil { fmt.Println("获取流列表失败:", err) } else { fmt.Printf("流列表: %v\n", resp.Items) } // 生成 RTMP 推流 URL(带鉴权签算) hubName := "my-hub" streamTitle := "stream001" pushURL := pili.RTMPPublishURL("push.example.com", hubName, streamTitle, 1800, "your-secret-key") fmt.Println("推流地址:", pushURL) // 生成 HLS 播放 URL playURL := pili.HLSPlayURL("play.example.com", hubName, streamTitle) fmt.Println("HLS 播放地址:", playURL) // 禁用直播流 err = manager.DisableStream(pili.DisableStreamRequest{ Hub: hubName, Stream: streamTitle, }) if err != nil { fmt.Println("禁用流失败:", err) } } ``` -------------------------------- ### Authentication Signature Source: https://context7.com/qiniu/go-sdk/llms.txt Details on using the `auth` package for Qiniu and Qbox signature methods, including HTTP request authentication and download URL signing. ```APIDOC ## Authentication Signature (`auth`) `auth.Credentials` provides Qiniu and Qbox signature methods for authenticating HTTP requests, signing private download URLs, and generating upload credentials. ### Initialize Credentials ```go mac := auth.New("your-access-key", "your-secret-key") ``` ### Sign Raw Data Used for purposes like signing private download URLs. ```go dataToSign := []byte("https://example.com/private/file.jpg?e=1893456000") token := mac.Sign(dataToSign) fmt.Println("Token:", token) ``` ### Add Qiniu Authentication Header to HTTP Request ```go req, _ := http.NewRequest("GET", "https://rs.qiniu.com/stat/bXktYnVja2V0OmhlbGxvLnR4dA==", nil) mac.AddToken(auth.TokenQiniu, req) fmt.Println("Authorization:", req.Header.Get("Authorization")) ``` ### Generate Management Credentials Used for v1 interfaces like `BucketManager`. ```go accessToken, err := mac.SignRequest(req) if err != nil { fmt.Println("SignRequest failed:", err) return } fmt.Println("Management Credentials:", accessToken) ``` ### Sign Private Download URL ```go deadline := time.Now().Add(time.Hour).Unix() rawURL := "https://example.com/private/photo.jpg" downloadToken := mac.Sign([]byte(fmt.Sprintf("%s?e=%d", rawURL, deadline))) fmt.Printf("Private Download URL: %s?e=%d&token=%s\n", rawURL, deadline, downloadToken) ``` ``` -------------------------------- ### Generate Upload Tokens with storagev2/uptoken Source: https://context7.com/qiniu/go-sdk/llms.txt Create upload policies and sign them with credentials to generate upload tokens for client or form uploads. Supports bucket-wide or object-specific policies with optional callbacks. ```go package main import ( "fmt" "time" "github.com/qiniu/go-sdk/v7/storagev2/credentials" "github.com/qiniu/go-sdk/v7/storagev2/uptoken" ) func main() { cred := credentials.NewCredentials("your-access-key", "your-secret-key") // 针对整个存储空间的上传策略,有效期 1 小时 policy, err := uptoken.NewPutPolicy("my-bucket", time.Now().Add(time.Hour)) if err != nil { panic(err) } // 针对特定对象的上传策略 policyWithKey, err := uptoken.NewPutPolicyWithKey("my-bucket", "photos/avatar.jpg", time.Now().Add(time.Hour)) if err != nil { panic(err) } // 设置回调 policyWithKey.SetCallbackURL("https://example.com/callback", "example.com"). SetCallbackBody(`{"key":"$(key)","size":$(fsize)}`, "application/json") // 生成上传凭证字符串(用于客户端 SDK 或表单上传) signer := uptoken.NewSigner(policy, cred) token, err := signer.GetUpToken(nil) if err != nil { panic(err) } fmt.Println("UpToken:", token) _ = policyWithKey } ``` -------------------------------- ### Manage Real-Time Communication with Go SDK Source: https://context7.com/qiniu/go-sdk/llms.txt Use rtc.Manager to generate RoomTokens for user authentication, manage RTC applications (create, query, update, delete), and control room users (list, kick). ```go package main import ( "fmt" "github.com/qiniu/go-sdk/v7/rtc" ) func main() { manager := rtc.NewManager(&rtc.Config{ AccessKey: "your-access-key", SecretKey: "your-secret-key", }) // 创建 App app, err := manager.CreateApp(rtc.CreateAppRequest{ Hub: "my-hub", Title: "我的 RTC 应用", MaxUsers: 10, NoAutoKickUser: false, }) if err != nil { fmt.Println("创建 App 失败:", err) return } fmt.Printf("App ID: %s\n", app.AppID) // 生成 RoomToken(用户加入房间凭证) access := rtc.RoomAccess{ AppID: app.AppID, RoomName: "room-001", UserID: "user-alice", ExpireAt: 1893456000, // Unix 时间戳 Permission: "admin", // "admin" 或 "user" } token, err := manager.GetRoomToken(access) if err != nil { fmt.Println("获取 RoomToken 失败:", err) return } fmt.Println("RoomToken:", token) // 列举房间在线用户 users, err := manager.ListUser(rtc.ListUserRequest{ AppID: app.AppID, RoomName: "room-001", }) if err != nil { fmt.Println("列举用户失败:", err) } else { fmt.Printf("在线用户数: %d\n", len(users.Users)) } } ``` -------------------------------- ### Trigger Media Processing with Go SDK Source: https://context7.com/qiniu/go-sdk/llms.txt Use media/apis.NewMedia to trigger and query data processing tasks like audio/video transcoding and image processing. Requires valid credentials and bucket/key information. ```go package main import ( "context" "fmt" "github.com/qiniu/go-sdk/v7/media/apis" pfopapi "github.com/qiniu/go-sdk/v7/media/apis/pfop" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" "github.com/qiniu/go-sdk/v7/storagev2/credentials" ) func main() { cred := credentials.NewCredentials("your-access-key", "your-secret-key") mediaClient := apis.NewMedia(&httpclient.Options{Credentials: cred}) ctx := context.Background() // 触发持久化处理(如视频转码) resp, err := mediaClient.Pfop(ctx, &pfopapi.Request{ Bucket: "my-bucket", Key: "videos/input.mp4", Fops: "avthumb/mp4/vcodec/libx264|saveas/bXktYnVja2V0OnZpZGVvcy9vdXRwdXQubXA0", NotifyURL: "https://example.com/notify", Force: 1, }, nil) if err != nil { fmt.Println("触发处理失败:", err) return } fmt.Printf("任务 ID: %s\n", resp.PersistentID) // 查询任务状态 status, err := mediaClient.Prefop(ctx, &struct{ PersistentID string }{resp.PersistentID}, nil) if err != nil { fmt.Println("查询状态失败:", err) return } fmt.Printf("任务状态: %+v\n", status) } ``` -------------------------------- ### Format Code with Gofmt Source: https://github.com/qiniu/go-sdk/blob/master/AGENTS.md Apply standard Go code formatting to the entire project. This command modifies files in place. ```bash gofmt -s -w . ``` -------------------------------- ### Go Build Tag for Unit Tests Source: https://github.com/qiniu/go-sdk/blob/master/AGENTS.md Use this build tag for Go files intended for unit tests. Unit tests should not depend on external services. ```go //go:build unit package xxx_test ``` -------------------------------- ### Identity and Access Management (iam) Source: https://context7.com/qiniu/go-sdk/llms.txt Create a client via `iam/apis.NewIam` to manage sub-accounts, user groups, and permission policies for fine-grained account permission control. ```APIDOC ## Identity and Access Management (`iam`) Create a client via `iam/apis.NewIam` to manage sub-accounts, user groups, and permission policies for fine-grained account permission control. ### Create Sub-account ```go user, err := iamClient.CreateUser(ctx, &iamreqs.Request{ Alias: "dev-alice", Password: "P@ssw0rd!", }, nil) ``` ### Query User List ```go users, err := iamClient.GetUsers(ctx, nil, nil) ``` ``` -------------------------------- ### Manage SMS with Go SDK Source: https://context7.com/qiniu/go-sdk/llms.txt Use sms.Manager to create signatures, templates, and send SMS messages. Ensure you have valid access keys and secret keys configured. ```go package main import ( "fmt" "github.com/qiniu/go-sdk/v7/auth" "github.com/qiniu/go-sdk/v7/sms" ) func main() { mac := auth.New("your-access-key", "your-secret-key") manager := sms.NewManager(mac) // 创建签名 sig, err := manager.CreateSignature(sms.CreateSignatureRequest{ Signature: "七牛云", SignatureType: "企业", }) if err != nil { fmt.Println("创建签名失败:", err) return } fmt.Printf("签名 ID: %s\n", sig.SignatureID) // 创建短信模板 tmpl, err := manager.CreateTemplate(sms.CreateTemplateRequest{ Name: "验证码模板", Template: "您的验证码是 ${code},5 分钟内有效。", Type: "verification", Description: "用户登录验证码", SignatureID: sig.SignatureID, }) if err != nil { fmt.Println("创建模板失败:", err) return } fmt.Printf("模板 ID: %s\n", tmpl.TemplateID) // 发送短信 sendResp, err := manager.SendMessage(sms.MessagesRequest{ SignatureID: sig.SignatureID, TemplateID: tmpl.TemplateID, Mobiles: []string{"13800138000", "13900139000"}, Parameters: map[string]interface{}{"code": "8964"}, }) if err != nil { fmt.Println("发送失败:", err) return } fmt.Printf("发送结果: %+v\n", sendResp) } ``` -------------------------------- ### Upload Files with storagev2/uploader Source: https://context7.com/qiniu/go-sdk/llms.txt Utilize UploadManager for flexible file uploads, automatically switching between form and multipart uploads. Supports uploading local files, io.Reader, and entire directories with configurable concurrency and callbacks. ```go package main import ( "context" "fmt" "strings" "time" "github.com/qiniu/go-sdk/v7/storagev2/credentials" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" "github.com/qiniu/go-sdk/v7/storagev2/uploader" "github.com/qiniu/go-sdk/v7/storagev2/uptoken" ) func main() { cred := credentials.NewCredentials("your-access-key", "your-secret-key") policy, _ := uptoken.NewPutPolicy("my-bucket", time.Now().Add(time.Hour)) signer := uptoken.NewSigner(policy, cred) manager := uploader.NewUploadManager(&uploader.UploadManagerOptions{ Options: httpclient.Options{Credentials: cred}, // 分片大小 8 MB,并发度 4 PartSize: 8 * 1024 * 1024, Concurrency: 4, }) ctx := context.Background() // 上传本地文件 objectName := "docs/readme.txt" err := manager.UploadFile(ctx, "/tmp/readme.txt", &uploader.ObjectOptions{ BucketName: "my-bucket", ObjectName: &objectName, UpToken: signer, }, nil) if err != nil { fmt.Println("上传失败:", err) return } fmt.Println("文件上传成功") // 上传 io.Reader(内存中的数据) content := strings.NewReader("Hello, Qiniu!") readerName := "hello.txt" err = manager.UploadReader(ctx, content, &uploader.ObjectOptions{ BucketName: "my-bucket", ObjectName: &readerName, UpToken: signer, }, nil) if err != nil { fmt.Println("Reader 上传失败:", err) return } fmt.Println("Reader 上传成功") // 批量上传目录 err = manager.UploadDirectory(ctx, "/tmp/data/", &uploader.DirectoryOptions{ BucketName: "my-bucket", UpToken: signer, ObjectConcurrency: 4, OnObjectUploaded: func(path string, info *uploader.UploadedObjectInfo) { fmt.Printf("已上传: %s (%d bytes)\n", path, info.Size) }, }) if err != nil { fmt.Println("目录上传失败:", err) } } ```