github.com/qiniu/go-sdk/v7@v7.27.0/examples/sandbox_create/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(), 60*time.Second) 30 defer cancel() 31 32 // 创建沙箱,templateID 需替换为实际可用的模板 ID 33 templateID := "base" 34 timeout := int32(300) 35 sb, err := c.Create(ctx, sandbox.CreateParams{ 36 TemplateID: templateID, 37 Timeout: &timeout, 38 }) 39 if err != nil { 40 log.Fatalf("创建沙箱失败: %v", err) 41 } 42 43 fmt.Printf("沙箱已创建: %s (模板: %s)\n", sb.ID(), sb.TemplateID()) 44 45 // 演示完毕,终止沙箱释放资源 46 killCtx, killCancel := context.WithTimeout(context.Background(), 10*time.Second) 47 defer killCancel() 48 if err := sb.Kill(killCtx); err != nil { 49 log.Printf("终止沙箱失败: %v", err) 50 } else { 51 fmt.Printf("沙箱 %s 已终止\n", sb.ID()) 52 } 53 }