github.com/qiniu/go-sdk/v7@v7.27.0/examples/sandbox_list/main.go (about) 1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 "os" 8 "time" 9 10 "github.com/qiniu/go-sdk/v7/sandbox" 11 ) 12 13 func main() { 14 apiKey := os.Getenv("QINIU_API_KEY") 15 if apiKey == "" { 16 log.Fatal("请设置 QINIU_API_KEY 环境变量") 17 } 18 19 apiURL := os.Getenv("QINIU_SANDBOX_API_URL") 20 21 c, err := sandbox.NewClient(&sandbox.Config{ 22 APIKey: apiKey, 23 Endpoint: apiURL, 24 }) 25 if err != nil { 26 log.Fatalf("创建客户端失败: %v", err) 27 } 28 29 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) 30 defer cancel() 31 32 // 列出所有运行中的沙箱 33 sandboxes, err := c.List(ctx, nil) 34 if err != nil { 35 log.Fatalf("列出沙箱失败: %v", err) 36 } 37 38 fmt.Printf("共 %d 个运行中的沙箱:\n", len(sandboxes)) 39 for _, sb := range sandboxes { 40 fmt.Printf(" - %s (模板: %s)\n", sb.SandboxID, sb.TemplateID) 41 } 42 43 // 按状态过滤列出沙箱 44 fmt.Println("\n=== 按状态过滤 ===") 45 states := []sandbox.SandboxState{sandbox.StateRunning} 46 filtered, err := c.List(ctx, &sandbox.ListParams{ 47 State: &states, 48 }) 49 if err != nil { 50 log.Fatalf("列出沙箱失败: %v", err) 51 } 52 fmt.Printf("共 %d 个 running 状态的沙箱\n", len(filtered)) 53 54 // 按一个或多个模板 ID / 名称过滤,最多可传 20 个值。 55 fmt.Println("\n=== 按模板过滤 ===") 56 templates := []string{"base"} 57 filteredByTemplate, err := c.List(ctx, &sandbox.ListParams{ 58 Template: &templates, 59 }) 60 if err != nil { 61 log.Fatalf("按模板列出沙箱失败: %v", err) 62 } 63 fmt.Printf("模板 %v 下共有 %d 个沙箱\n", templates, len(filteredByTemplate)) 64 65 // 批量获取沙箱指标 66 if len(sandboxes) > 0 { 67 fmt.Println("\n=== 批量获取沙箱指标 ===") 68 ids := make([]string, 0, len(sandboxes)) 69 for _, sb := range sandboxes { 70 ids = append(ids, sb.SandboxID) 71 } 72 metrics, err := c.GetSandboxesMetrics(ctx, &sandbox.GetSandboxesMetricsParams{ 73 SandboxIds: ids, 74 }) 75 if err != nil { 76 fmt.Printf("获取批量指标失败: %v\n", err) 77 } else { 78 fmt.Printf("获取到 %d 个沙箱的指标数据\n", len(metrics.Sandboxes)) 79 } 80 } 81 }