Qiniu Go SDK v7

repository·master·Indexed 41 days ago

https://github.com/qiniu/go-sdk

A client library for interacting with Qiniu cloud services, including Object Storage (RS), CDN, Real-Time Communication (RTC), and Video processing. It provides specialized managers for Pili Streaming, QVS (Qiniu Video Service), and Linking for IoT device lifecycle and VOD segment management. Requires Go 1.22 or higher.

Tokens
6.7K
Snippets
18
Records
27
Agent score
100%

What's inside Qiniu Go SDK

  1. Overview of Qiniu Go SDK functional modules

    master

    The SDK is organized into several functional modules covering Object Storage, Cloud Services, and Infrastructure:

    • storagev2: Core v2 API with typed requests/responses, auto-region detection, and connection pooling.
    • storagev2/uploader: Manages uploads (automatically selects between form or chunked upload).
    • storagev2/downloader: Manages downloads with concurrent chunk support.
    • storagev2/objects: Object management via a chainable API (query, copy, move, delete, etc.).
    • storagev2/credentials: Credential management via CredentialsProvider interface.
    • storagev2/uptoken: Upload token management using PutPolicy.
    • storagev2/region: Region information and endpoint management.
    • storagev2/apis: Low-level typed APIs.
    • storage: Legacy v1 API.

    Other Cloud Services

    • auth: Authentication and signing (AK/SK, request signing, callback verification).
    • cdn: CDN acceleration (refresh, prefetch, traffic/bandwidth queries, logs).
    • pili: Live streaming (Hub/Stream management, URL generation).
    • rtc: Real-time audio/video (RoomToken, room management).
    • sms: SMS services (sending, signature/template management).
    • qvs: Video surveillance (GB/T 28181 device management, recording, snapshots).
    • linking: IoT device connectivity (device management, keys).
    • iam: Identity and Access Management (sub-accounts, groups, policies).
    • media: Multimedia data processing (triggering and querying persistent processing).
    • audit: Audit logs (account operation auditing).
    • sandbox: Sandbox services (lifecycle, file ops, command execution).

    Infrastructure

    • client: Underlying HTTP client.
    • storagev2/http_client: storagev2 specific HTTP client and options.
    • reqid: Request ID propagation.
    • conf: Global SDK configuration.
  2. Pili Streaming API Capabilities

    master

    The Pili SDK provides programmatic access to the following functional modules:

    URL Generation and Signing

    • Generate RTMP/SRT push URLs and RTMP/HLS/HDL(FLV) playback URLs.
    • Perform live stream authentication (push URL signing).
    • Perform anti-leech protection (playback URL timestamp signing).

    Live Space Management (Hub)

    • Query lists and details of live streaming spaces (hubs).
    • Configure security (push authentication), HLS low latency, persistence (storage), and snapshot (cover image) settings for a hub.

    Domain Management (Domain)

    • Query and manage domains associated with a hub.
    • Bind new live domains or unbind existing ones.
    • Configure VOD domains, SSL certificates, and URL rewrite rules.

    Stream Management (Stream)

    • Query live stream lists and specific stream information.
    • Disable live streams and query online stream status (individual or batch).
    • Access stream history, record live streams for playback, save snapshots, and modify transcoding configurations.

    Data Statistics (Stat)

    • Monitor upflow and downflow traffic.
    • Track usage for live transcoding, content moderation (nrop), caster (studio), and Pub services.
  3. How to use Dtokens for efficient video playback

    master

    When a user requests video-related APIs (like playback), performing the request through your business server as a proxy creates long request paths and increases latency.

    Recommended Pattern:

    1. The client requests a token from your server.
    2. Your server uses the SDK to generate a VodToken (or StatusToken) using the linking.Manager.
    3. Your server returns this token to the client.
    4. The client uses the token to request video playback APIs directly from Qiniu. This improves the playback experience and reduces server load.
  4. Install the Qiniu Go SDK

    master

    To use the Qiniu Go SDK in your project, install the v7 version using go get. This SDK requires Go 1.22 or higher.

    Using CLI:

    go get github.com/qiniu/go-sdk/v7

    Using go.mod:

    require github.com/qiniu/go-sdk/v7 v7.28.1
  5. Configure the Linking Manager

    master

    To use the Linking service, initialize a linking.Manager using an auth.Mac instance. You will need your Qiniu AccessKey, SecretKey, and a pre-created Appid.

    package main
    
    import (
    	"github.com/qiniu/go-sdk/v7/auth"
    	"github.com/qiniu/go-sdk/v7/linking"
    )
    
    var (
    	AccessKey = "<QINIU ACCESS KEY>"
    	SecretKey = "<QINIU SECRET KEY>"
    	Appid     = "<Appid>"
    )
    
    func main() {
    	mac := auth.New(AccessKey, SecretKey)
    	manager := linking.NewManager(mac, nil)
    	// Use manager to call Linking APIs
    }
  6. Initialize the Pili Streaming Manager

    master

    To use the Pili Streaming Cloud Server-Side Library, you must first initialize a pili.Manager using your Qiniu AccessKey and SecretKey. This manager serves as the entry point for managing live streaming hubs, domains, streams, and statistics.

    package main
    
    import (
    	"github.com/qiniu/go-sdk/v7/pili"
    )
    
    var (
    	AccessKey = "<QINIU ACCESS KEY>"
    	SecretKey = "<QINIU SECRET KEY>"
    )
    
    func main() {
    	conf := pili.ManagerConfig{AccessKey: AccessKey, SecretKey: SecretKey}
    	manager := pili.NewManager(conf)
    	_ = manager
    }
  7. Run Qiniu Go SDK examples

    master

    Each subdirectory in the examples/ directory contains an independent example program. You can run any specific example using the go run command followed by the path to that example's directory.

    go run ./examples/<name>/
  8. Initialize the QVS Manager

    master

    To use the QVS (Qiniu Video Service) library, you must first authenticate using your Qiniu AccessKey and SecretKey. Create an authentication object using auth.New and pass it to qvs.NewManager to obtain a manager instance for managing namespaces, streams, and templates.

    package main
    
    import (
    	"github.com/qiniu/go-sdk/v7/auth"
    	"github.com/qiniu/go-sdk/v7/qvs"
    )
    
    var (
    	AccessKey = "<QINIU ACCESS KEY>"
    	SecretKey = "<QINIU SECRET KEY>"
    )
    
    func main() {
    	mac := auth.New(AccessKey, SecretKey)
    	manager := qvs.NewManager(mac, nil)
    	// Use manager to perform QVS operations
    }
  9. Overview of the Qiniu Go SDK v7.x

    master

    The github.com/qiniu/go-sdk is the v7.x version of the Qiniu Go SDK. It provides core functionalities for data upload, download, management, and CDN services.

    Requirements:

    • Go version >= 1.10.0

    Core Modules:

    • auth: Provides authentication and authorization methods.
    • conf: Provides configuration management methods.
    • cdn: Provides Content Delivery Network (CDN) related functionalities.
    • storage: Provides Object Storage related functionalities.
  10. Configure Client Debugging and User Agent

    master

    You can customize how the SDK identifies itself and how much information it logs during development.

    Enable Debug Mode

    Calling TurnOnDebug() enables debug logging. When DebugMode is true, the client will log request and response details (using httptrace and httputil.DumpRequest/Response).

    Set Custom User Agent

    Use SetAppName(userApp string) to set a custom application name in the User-Agent header. This is useful for tracking which applications are making requests in your logs.

    Deep Debugging

    Setting the global variable DeepDebugInfo = true will cause the client to include the request/response bodies in the debug logs (provided the content type is JSON or Form).

    import "github.com/qiniu/go-sdk/v7/client"
    
    func init() {
        client.TurnOnDebug()
        client.SetAppName("my-awesome-app")
    }
  11. Quick Start: Upload a file to Object Storage (v2 API)

    master

    This example demonstrates how to initialize credentials, create an upload policy, and use the uploader.UploadManager to upload a file using the recommended storagev2 API.

    1. Obtain your AccessKey and SecretKey from the Qiniu Portal.
    2. Use credentials.NewCredentials to create your identity.
    3. Use uptoken.NewPutPolicy to define the target bucket and expiration.
    4. Use uploader.NewUploadManager with http_client.Options to manage the upload process.
    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("上传成功")
    }
  12. Manage device keys in Linking

    master

    Manage access keys (DAK) for devices using the following methods:

    • AddDeviceKey(appid, device string): Create a new device key.
    • QueryDeviceKey(appid, device string) ([]string, error): List keys associated with a device.
    • DeleteDeviceKey(appid, device, dak string): Delete a specific device key.
    • UpdateDeviceKeyState(appid, device, dak string, state int): Enable or disable a device key (e.g., state: 1 to enable).
    • CloneDeviceKey(appid, fromdevice, todevice string, cleanSelfKeys, deleteDevice bool, deviceAccessKey string) ([]string, error): Clone a device key from one device to another.
    • QueryAppidDeviceNameByAccessKey(dak string) (appid, device string, err error): Look up the appid and device name using a specific device access key (DAK).
    // Example: Clone a device key
    keys, err := manager.CloneDeviceKey(Appid, device1, device2, false, false, dak1)
    
    // Example: Query device info by access key
    appid, device, err := manager.QueryAppidDeviceNameByAccessKey(dak)