github.com/qiniu/go-sdk/v7@v7.27.0/examples/sandbox_injection_rules/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/auth"
    11  	"github.com/qiniu/go-sdk/v7/internal/env"
    12  	"github.com/qiniu/go-sdk/v7/sandbox"
    13  )
    14  
    15  func main() {
    16  	apiKey := os.Getenv("QINIU_API_KEY")
    17  	if apiKey == "" {
    18  		log.Fatal("请设置 QINIU_API_KEY 环境变量")
    19  	}
    20  
    21  	accessKey, secretKey := env.CredentialsFromEnvironment()
    22  	if accessKey == "" || secretKey == "" {
    23  		log.Fatal("请设置 QINIU_ACCESS_KEY 和 QINIU_SECRET_KEY 环境变量")
    24  	}
    25  
    26  	apiURL := os.Getenv("QINIU_SANDBOX_API_URL")
    27  
    28  	c, err := sandbox.NewClient(&sandbox.Config{
    29  		APIKey: apiKey,
    30  		Credentials: &auth.Credentials{
    31  			AccessKey: accessKey,
    32  			SecretKey: []byte(secretKey),
    33  		},
    34  		Endpoint: apiURL,
    35  	})
    36  	if err != nil {
    37  		log.Fatalf("创建客户端失败: %v", err)
    38  	}
    39  
    40  	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
    41  	defer cancel()
    42  
    43  	// 1. 创建注入规则(HTTP 自定义注入)
    44  	fmt.Println("=== 创建注入规则 ===")
    45  	headers := map[string]string{
    46  		"Authorization": "Bearer real_token",
    47  	}
    48  	ifHeaders := map[string]string{
    49  		"X-Injection-Scope": "demo",
    50  	}
    51  	ifQueries := map[string]string{
    52  		"inject": "true",
    53  	}
    54  	rule, err := c.CreateInjectionRule(ctx, sandbox.CreateInjectionRuleParams{
    55  		Name: "example-rule",
    56  		Injection: sandbox.InjectionSpec{
    57  			HTTP: &sandbox.HTTPInjection{
    58  				BaseURL:   "https://httpbin.org",
    59  				Headers:   &headers,
    60  				IfHeaders: &ifHeaders,
    61  				IfQueries: &ifQueries,
    62  			},
    63  		},
    64  	})
    65  	if err != nil {
    66  		log.Fatalf("创建注入规则失败: %v", err)
    67  	}
    68  	ruleID := rule.RuleID
    69  	fmt.Printf("规则已创建: ID=%s, 名称=%s\n", ruleID, rule.Name)
    70  	fmt.Printf("  创建时间: %s\n", rule.CreatedAt.Format(time.RFC3339))
    71  
    72  	// 确保测试结束时清理
    73  	defer func() {
    74  		fmt.Println("\n=== 删除注入规则 ===")
    75  		if err := c.DeleteInjectionRule(context.Background(), ruleID); err != nil {
    76  			fmt.Printf("删除注入规则失败: %v\n", err)
    77  		} else {
    78  			fmt.Printf("规则 %s 已删除\n", ruleID)
    79  		}
    80  	}()
    81  
    82  	// 2. 获取注入规则详情
    83  	fmt.Println("\n=== 获取注入规则详情 ===")
    84  	detail, err := c.GetInjectionRule(ctx, ruleID)
    85  	if err != nil {
    86  		log.Fatalf("获取注入规则失败: %v", err)
    87  	}
    88  	fmt.Printf("规则: ID=%s, 名称=%s\n", detail.RuleID, detail.Name)
    89  	if detail.Injection.HTTP != nil {
    90  		fmt.Printf("  HTTP BaseURL: %s\n", detail.Injection.HTTP.BaseURL)
    91  		if detail.Injection.HTTP.Headers != nil {
    92  			fmt.Printf("  注入 Headers: %v\n", *detail.Injection.HTTP.Headers)
    93  		}
    94  		if detail.Injection.HTTP.IfHeaders != nil {
    95  			fmt.Printf("  Header 匹配条件: %v\n", *detail.Injection.HTTP.IfHeaders)
    96  		}
    97  		if detail.Injection.HTTP.IfQueries != nil {
    98  			fmt.Printf("  Query 匹配条件: %v\n", *detail.Injection.HTTP.IfQueries)
    99  		}
   100  	}
   101  
   102  	// 3. 更新注入规则
   103  	fmt.Println("\n=== 更新注入规则 ===")
   104  	newName := "example-rule-updated"
   105  	newHeaders := map[string]string{
   106  		"Authorization": "Bearer updated_token",
   107  		"X-Custom":      "custom-value",
   108  	}
   109  	newIfHeaders := map[string]string{
   110  		"X-Injection-Scope": "updated-demo",
   111  	}
   112  	newIfQueries := map[string]string{
   113  		"inject": "updated",
   114  	}
   115  	updated, err := c.UpdateInjectionRule(ctx, ruleID, sandbox.UpdateInjectionRuleParams{
   116  		Name: &newName,
   117  		Injection: &sandbox.InjectionSpec{
   118  			HTTP: &sandbox.HTTPInjection{
   119  				BaseURL:   "https://httpbin.org",
   120  				Headers:   &newHeaders,
   121  				IfHeaders: &newIfHeaders,
   122  				IfQueries: &newIfQueries,
   123  			},
   124  		},
   125  	})
   126  	if err != nil {
   127  		log.Fatalf("更新注入规则失败: %v", err)
   128  	}
   129  	fmt.Printf("规则已更新: 名称=%s, 更新时间=%s\n", updated.Name, updated.UpdatedAt.Format(time.RFC3339))
   130  
   131  	// 4. 列出所有注入规则
   132  	fmt.Println("\n=== 列出所有注入规则 ===")
   133  	rules, err := c.ListInjectionRules(ctx)
   134  	if err != nil {
   135  		log.Fatalf("列出注入规则失败: %v", err)
   136  	}
   137  	fmt.Printf("共 %d 条规则:\n", len(rules))
   138  	for _, r := range rules {
   139  		fmt.Printf("  - ID=%s, 名称=%s, 创建时间=%s\n",
   140  			r.RuleID, r.Name, r.CreatedAt.Format(time.RFC3339))
   141  	}
   142  
   143  	// 5. 使用注入规则创建沙箱(通过 ID 引用)
   144  	fmt.Println("\n=== 使用注入规则创建沙箱 ===")
   145  	sb, info, err := c.CreateAndWait(ctx, sandbox.CreateParams{
   146  		TemplateID: "base",
   147  		Injections: &[]sandbox.SandboxInjectionSpec{
   148  			{ByID: &ruleID},
   149  		},
   150  	})
   151  	if err != nil {
   152  		log.Fatalf("创建沙箱失败: %v", err)
   153  	}
   154  	defer func() {
   155  		fmt.Println("\n=== 销毁沙箱 ===")
   156  		_ = sb.Kill(context.Background())
   157  		fmt.Println("沙箱已销毁")
   158  	}()
   159  	fmt.Printf("沙箱已创建: ID=%s, 状态=%s\n", sb.ID(), info.State)
   160  
   161  	// 在沙箱内验证注入规则生效
   162  	cmd := `curl -sSL -X GET "https://httpbin.org/bearer?inject=updated" -H "accept: application/json" -H "Authorization: Bearer fake_token" -H "X-Injection-Scope: updated-demo"`
   163  	fmt.Printf("\n执行命令:\n$ %s\n", cmd)
   164  	result, err := sb.Commands().Run(ctx, cmd)
   165  	if err != nil {
   166  		log.Fatalf("执行命令失败: %v", err)
   167  	}
   168  	fmt.Printf("退出码: %d\n", result.ExitCode)
   169  	fmt.Printf("输出:\n%s\n", result.Stdout)
   170  
   171  	// 6. 删除注入规则(通过 defer 执行)
   172  }