### 30 秒快速开始 Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/QUICK-REFERENCE.md Quick start example demonstrating how to initialize the SDK and make a DescribeVpcs call. ```go package main import ( "log" "github.com/volcengine/volcengine-go-sdk/service/vpc" "github.com/volcengine/volcengine-go-sdk/volcengine" "github.com/volcengine/volcengine-go-sdk/volcengine/session" ) func main() { sess, _ := session.NewSession(volcengine.NewConfig(). WithRegion("cn-beijing"). WithAkSk("ak", "sk")) resp, _ := vpc.New(sess).DescribeVpcs(&vpc.DescribeVpcsInput{ PageNumber: volcengine.Int64(1), }) for _, v := range resp.Vpcs { log.Println(volcengine.StringValue(v.VpcId)) } } ``` -------------------------------- ### Full Configuration Example Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/01-config-reference.md Example demonstrating a comprehensive configuration setup with various options. ```go config := volcengine.NewConfig(). WithRegion("cn-beijing"). WithAkSk("your-ak", "your-sk"). WithEndpoint("vpc.cn-beijing.volcengineapi.com"). WithMaxRetries(3). WithLogger(volcengine.NewDefaultLogger()). WithLogLevel(volcengine.LogDebug). WithHTTPProxy("http://proxy.example.com:8080") ``` -------------------------------- ### Configuration File Example Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/README.md Example of the configuration file format. ```ini [default] region = cn-beijing output = json [profile-name] region = cn-shanghai output = json ``` -------------------------------- ### Credentials File Example Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/README.md Example of the credentials file format. ```ini [default] volcengine_access_key = your-access-key-id volcengine_secret_key = your-secret-key [profile-name] volcengine_access_key = another-access-key-id volcengine_secret_key = another-secret-key ``` -------------------------------- ### Start/Stop/Reboot Instances Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/08-common-service-patterns.md Examples for starting, stopping, and rebooting ECS instances using the Go SDK. ```go // 启动实例 ecsClient.StartInstances(&ecs.StartInstancesInput{ InstanceIds: volcengine.StringSlice([]string{"i-123"}), }) // 停止实例 ecsClient.StopInstances(&ecs.StopInstancesInput{ InstanceIds: volcengine.StringSlice([]string{"i-123"}), Force: volcengine.Bool(false), }) // 重启实例 ecsClient.RebootInstances(&ecs.RebootInstancesInput{ InstanceIds: volcengine.StringSlice([]string{"i-123"}), Force: volcengine.Bool(false), }) ``` -------------------------------- ### VPC DescribeVpcs Example Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/README.MD Example code demonstrating how to use the VPC client to describe VPCs. ```go package main import ( "fmt" "github.com/volcengine/volcengine-go-sdk/service/vpc" "github.com/volcengine/volcengine-go-sdk/volcengine" "github.com/volcengine/volcengine-go-sdk/volcengine/credentials" "github.com/volcengine/volcengine-go-sdk/volcengine/session" ) func main() { var ( ak string sk string region string config *volcengine.Config sess *session.Session client *vpc.VPC resp *vpc.DescribeVpcsOutput err error ) ak = "your ak" sk = "your sk" region = "cn-beijing" config = volcengine.NewConfig(). WithCredentials(credentials.NewStaticCredentials(ak, sk, "")). WithRegion(region) sess, err = session.NewSession(config) if err != nil { panic(err) } client = vpc.New(sess) resp, err = client.DescribeVpcs(&vpc.DescribeVpcsInput{ PageNumber: volcengine.Int64(1), PageSize: volcengine.Int64(10), }) if err != nil { panic(err) } fmt.Println(&resp) } ``` -------------------------------- ### Endpoint Rules Example Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/01-config-reference.md Examples showing how to set endpoints for regional and global services. ```go // Regional service config.WithEndpoint("ecs.cn-beijing.volcengineapi.com") ``` ```go // Global service config.WithEndpoint("iam.volcengineapi.com") ``` -------------------------------- ### Minimal Configuration Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/01-config-reference.md Example of setting up a minimal configuration with region and AK/SK. ```go config := volcengine.NewConfig(). WithRegion("cn-beijing"). WithAkSk("your-ak", "your-sk") ``` -------------------------------- ### Configuration Merging Example Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/01-config-reference.md Illustrates merging configurations using MergeIn. ```go baseConfig := volcengine.NewConfig(). WithRegion("cn-beijing"). WithMaxRetries(3) sessionConfig := volcengine.NewConfig().WithDebug(true) baseConfig.MergeIn(sessionConfig) ``` -------------------------------- ### LogLevel Example Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/04-types-and-utilities.md Example of setting the log level for a configuration. ```go config.WithLogLevel(*volcengine.LogLevel(volcengine.LogDebug)) ``` -------------------------------- ### WriteAtBuffer Example Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/04-types-and-utilities.md Example demonstrating the usage of WriteAtBuffer for S3 download management with concurrent writes. ```go // 用于 S3 下载管理 buf := volcengine.NewWriteAtBuffer(make([]byte, 0)) // 多个 Goroutine 可以并发调用 WriteAt buf.WriteAt(chunk1, 0) buf.WriteAt(chunk2, len(chunk1)) // 获取完整内容 data := buf.Bytes() ``` -------------------------------- ### Create Resource Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/06-client-reference.md Example of creating a new VPC resource. ```go resp, err := vpcClient.CreateVpc(&vpc.CreateVpcInput{ VpcName: volcengine.String("my-vpc"), CidrBlock: volcengine.String("10.0.0.0/16"), }) if err != nil { log.Printf("Failed to create VPC: %v", err) return } vpcID := volcengine.StringValue(resp.VpcId) ``` -------------------------------- ### File Upload Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/QUICK-REFERENCE.md Example of uploading a file using the SDK, handling it as a ReadSeekCloser. ```go import "os" file, _ := os.Open("large-file.bin") defer file.Close() rsc := volcengine.ReadSeekCloser(file) input := &service.UploadInput{ Body: rsc, } client.Upload(input) ``` -------------------------------- ### STS AssumeRoleWithSAML Example - Option 1: Using WithOptions (recommended) Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/docs/1-Credentials.md Example of using SAMLCredentialsProviderWithOptions to configure SAML credentials with options. ```go package main import ( "github.com/volcengine/volcengine-go-sdk/volcengine" "github.com/volcengine/volcengine-go-sdk/volcengine/credentials" "github.com/volcengine/volcengine-go-sdk/volcengine/session" ) func main() { p := credentials.NewSAMLCredentialsProviderWithOptions( "trn:iam::1234567890:role/saml-role", // Role TRN (required) "trn:iam::1234567890:saml-provider/MyIdp", // SAML provider TRN (required) "BASE64_ENCODED_SAML_RESPONSE_FROM_IDP", // SAML assertion (required) func(o *credentials.SAMLProviderOptions) { // o.DurationSeconds = 3600 // Validity period, default 3600 // o.MaxRetries = volcengine.Int(3) // optional: retry attempts; nil defaults to 3, 0 disables // o.RetryInterval = 1 * time.Second // optional: sleep between retries; <= 0 falls back to 1s }, ) config := volcengine.NewConfig(). WithRegion("cn-beijing"). WithCredentials(credentials.NewCredentials(p)) sess, err := session.NewSession(config) if err != nil { panic(err) } } ``` -------------------------------- ### AssumeRoleWithSAML - Using WithOptions Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/docs/1-Credentials-zh.md Example of configuring SAML credentials provider using WithOptions, the recommended method. ```go package main import ( "github.com/volcengine/volcengine-go-sdk/volcengine" "github.com/volcengine/volcengine-go-sdk/volcengine/credentials" "github.com/volcengine/volcengine-go-sdk/volcengine/session" ) func main() { p := credentials.NewSAMLCredentialsProviderWithOptions( "trn:iam::1234567890:role/saml-role", // 角色 TRN(必填) "trn:iam::1234567890:saml-provider/MyIdp", // SAML 提供者 TRN(必填) "BASE64_ENCODED_SAML_RESPONSE_FROM_IDP", // SAML 断言(必填) func(o *credentials.SAMLProviderOptions) { // o.DurationSeconds = 3600 // 有效期,默认 3600 // o.MaxRetries = volcengine.Int(3) // 可选:失败时额外重试次数;nil 默认 3,0 表示关闭重试 // o.RetryInterval = 1 * time.Second // 可选:重试间隔;<= 0 时回退到 1s }, ) config := volcengine.NewConfig(). WithRegion("cn-beijing"). WithCredentials(credentials.NewCredentials(p)) sess, err := session.NewSession(config) if err != nil { panic(err) } } ``` -------------------------------- ### Standard Endpoint Resolution Code Example Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/docs/2-Endpoint.md Code example showing how to use the Standard Endpoint Resolver with DualStack enabled. ```go package main import ( "github.com/volcengine/volcengine-go-sdk/volcengine" "github.com/volcengine/volcengine-go-sdk/volcengine/credentials" "github.com/volcengine/volcengine-go-sdk/volcengine/endpoints" "github.com/volcengine/volcengine-go-sdk/volcengine/session" ) func main() { regionId := "cn-beijing" config := volcengine.NewConfig(). WithCredentials(credentials.NewEnvCredentials()). WithEndpointResolver(endpoints.NewStandardEndpointResolver()). WithRegion(regionId). WithUseDualStack(true) sess, err := session.NewSession(config) if err != nil { panic(err) } } ``` -------------------------------- ### STS AssumeRoleWithSAML Example - Option 2: Using convenience constructor Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/docs/1-Credentials.md Example of using the convenience constructor for SAMLCredentialsProvider. ```go package main import ( "time" "github.com/volcengine/volcengine-go-sdk/volcengine" "github.com/volcengine/volcengine-go-sdk/volcengine/credentials" "github.com/volcengine/volcengine-go-sdk/volcengine/session" ) func main() { p := credentials.NewSAMLCredentialsProvider( "trn:iam::1234567890:role/saml-role", // RoleTrn "trn:iam::1234567890:saml-provider/MyIdp", // SAMLProviderTrn "BASE64_ENCODED_SAML_RESPONSE_FROM_IDP", // SAMLAssertion ) p.DurationSeconds = 3600 p.MaxRetries = volcengine.Int(3) // optional extra retry attempts; nil defaults to 3, 0 disables retries p.RetryInterval = 1 * time.Second // optional sleep between retries; <= 0 falls back to 1s config := volcengine.NewConfig(). WithRegion("cn-beijing"). WithCredentials(credentials.NewCredentials(p)) sess, err := session.NewSession(config) if err != nil { panic(err) } } ``` -------------------------------- ### Complete Error Handling Example Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/07-error-handling.md A full Go program demonstrating how to initialize the SDK, make an API call, and handle potential errors. ```go package main import ( "log" "github.com/volcengine/volcengine-go-sdk/service/vpc" "github.com/volcengine/volcengine-go-sdk/volcengine" "github.com/volcengine/volcengine-go-sdk/volcengine/credentials" "github.com/volcengine/volcengine-go-sdk/volcengine/session" ) func main() { config := volcengine.NewConfig(). WithRegion("cn-beijing"). WithAkSk("ak", "sk") sess, _ := session.NewSession(config) client := vpc.New(sess) resp, err := client.DescribeVpcs(&vpc.DescribeVpcsInput{ PageNumber: volcengine.Int64(1), PageSize: volcengine.Int64(10), }) if err != nil { handleError(err) return } log.Println("Success!") for _, v := range resp.Vpcs { log.Println(volcengine.StringValue(v.VpcId)) } } func handleError(err error) { if aerr, ok := err.(volcengine.Error); ok { switch aerr.Code() { case "InvalidParameter": log.Println("参数无效,请检查输入") case "Unauthorized": log.Println("认证失败,请检查凭证") case "ServiceUnavailable": log.Println("服务暂时不可用") default: log.Printf("API Error: %s - %s", aerr.Code(), aerr.Message()) } } else { log.Printf("System Error: %v", err) } } ``` -------------------------------- ### AssumeRoleWithSAML - Using Convenience Constructor Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/docs/1-Credentials-zh.md Example of configuring SAML credentials provider using a convenience constructor. ```go package main import ( "time" "github.com/volcengine/volcengine-go-sdk/volcengine" "github.com/volcengine/volcengine-go-sdk/volcengine/credentials" "github.com/volcengine/volcengine-go-sdk/volcengine/session" ) func main() { p := credentials.NewSAMLCredentialsProvider( "trn:iam::1234567890:role/saml-role", // RoleTrn "trn:iam::1234567890:saml-provider/MyIdp", // SAMLProviderTrn "BASE64_ENCODED_SAML_RESPONSE_FROM_IDP", // SAMLAssertion ) p.DurationSeconds = 3600 p.MaxRetries = volcengine.Int(3) // 可选:失败时额外重试次数;nil 默认 3,0 表示关闭重试 p.RetryInterval = 1 * time.Second // 可选:重试间隔;<= 0 时回退到 1s config := volcengine.NewConfig(). WithRegion("cn-beijing"). WithCredentials(credentials.NewCredentials(p)) sess, err := session.NewSession(config) if err != nil { panic(err) } } ``` -------------------------------- ### Using Service Clients Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/02-session-reference.md Example of creating VPC and ECS clients using a session. ```go sess, err := session.NewSession(volcengine.NewConfig(). WithRegion("cn-beijing"). WithAkSk("ak", "sk")) if err != nil { panic(err) } // Create VPC client vpcClient := vpc.New(sess) // Create ECS client ecsClient := ecs.New(sess) ``` -------------------------------- ### AssumeRoleOIDC - Using WithOptions Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/docs/1-Credentials-zh.md Example of configuring OIDC credentials provider using WithOptions, which is the recommended approach. ```go func main() { p := credentials.NewOIDCCredentialsProviderWithOptions( "/path/to/oidc_token_file", // OIDC Token 文件路径(必填) "Your Role Trn", // 角色 TRN(必填) func(o *credentials.OIDCProviderOptions) { // o.RoleSessionName = "" // env: VOLCENGINE_OIDC_ROLE_SESSION_NAME(可选) // o.Policy = "" // env: VOLCENGINE_OIDC_ROLE_POLICY(可选) // o.Endpoint = "" // env: VOLCENGINE_OIDC_STS_ENDPOINT(可选) // o.DurationSeconds = 3600 // 有效期,默认 3600 // o.MaxRetries = volcengine.Int(3) // 可选:失败时额外重试次数;nil 默认 3,0 表示关闭重试 // o.RetryInterval = 1 * time.Second // 可选:重试间隔;<= 0 时回退到 1s }, ) config := volcengine.NewConfig(). WithRegion("cn-beijing"). WithCredentials(credentials.NewCredentials(p)) sess, err := session.NewSession(config) if err != nil { panic(err) } svc := vpc.New(sess) resp, err := svc.DescribeVpcs(&vpc.DescribeVpcsInput{}) if err != nil { panic(err) } fmt.Println(resp) } ``` -------------------------------- ### Custom Endpoint Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/docs/2-Endpoint.md Example of configuring a custom endpoint for the SDK. ```go func main() { region := "cn-beijing" config := volcengine.NewConfig(). WithCredentials(credentials.NewEnvCredentials()). WithRegion(region). WithEndpoint("..volcengineapi.com") sess, err := session.NewSession(config) if err != nil { panic(err) } } ``` -------------------------------- ### Create VPC Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/08-common-service-patterns.md Example for creating a new VPC with a specified name and CIDR block. ```go resp, err := vpcClient.CreateVpc(&vpc.CreateVpcInput{ VpcName: volcengine.String("my-vpc"), CidrBlock: volcengine.String("10.0.0.0/16"), }) if err != nil { log.Printf("Failed to create VPC: %v", err) return } vpcId := volcengine.StringValue(resp.VpcId) log.Printf("Created VPC: %s", vpcId) ``` -------------------------------- ### Create Session with Credentials Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/02-session-reference.md Example of creating a session with explicit static credentials. ```go sess, err := session.NewSession(volcengine.NewConfig(). WithRegion("cn-beijing"). WithCredentials(credentials.NewStaticCredentials("ak", "sk", ""))) if err != nil { panic(err) } ``` -------------------------------- ### Create Load Balancer Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/08-common-service-patterns.md Example for creating an ALB load balancer. ```go import "github.com/volcengine/volcengine-go-sdk/service/alb" resp, err := albClient.CreateLoadBalancer(&alb.CreateLoadBalancerInput{ LoadBalancerName: volcengine.String("my-lb"), SubnetIds: volcengine.StringSlice([]string{"subnet-123", "subnet-456"}), LoadBalancerType: volcengine.String("application"), }) if err != nil { return } lbId := volcengine.StringValue(resp.LoadBalancerId) ``` -------------------------------- ### Custom Endpoint Setting Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/README.MD Example code for setting a custom endpoint for the SDK. ```go config = volcengine.NewConfig(). WithCredentials(credentials.NewStaticCredentials(ak, sk, "")). WithRegion(region).WithEndpoint("ecs.cn-beijing-autodriving.volcengineapi.com") ``` -------------------------------- ### List Operations (Pagination) Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/06-client-reference.md Example of paginating through a list of resources, such as VPCs. ```go var pageNumber int64 = 1 for { resp, err := vpcClient.DescribeVpcs(&vpc.DescribeVpcsInput{ PageNumber: volcengine.Int64(pageNumber), PageSize: volcengine.Int64(20), }) if err != nil { break } for _, vpc := range resp.Vpcs { // 处理 VPC } if !volcengine.BoolValue(resp.HasMore) { break } pageNumber++ } ``` -------------------------------- ### Describe VPC List Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/08-common-service-patterns.md Example of how to describe a list of VPCs, including pagination and optional filtering by VPC IDs. ```go import "github.com/volcengine/volcengine-go-sdk/service/vpc" resp, err := vpcClient.DescribeVpcs(&vpc.DescribeVpcsInput{ PageNumber: volcengine.Int64(1), PageSize: volcengine.Int64(20), // Optional filter conditions VpcIds: volcengine.StringSlice([]string{"vpc-123", "vpc-456"}), }) if err != nil { log.Printf("Error: %v", err) return } for _, v := range resp.Vpcs { log.Printf("VPC ID: %s, Name: %s", volcengine.StringValue(v.VpcId), volcengine.StringValue(v.VpcName)) } ``` -------------------------------- ### Create Instance Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/08-common-service-patterns.md Example for creating ECS instances, specifying image, type, count, subnet, and security group. ```go import "github.com/volcengine/volcengine-go-sdk/service/ecs" resp, err := ecsClient.RunInstances(&ecs.RunInstancesInput{ ImageId: volcengine.String("image-123"), InstanceType: volcengine.String("ecs.g1.large"), InstanceCount: volcengine.Int64(1), SubnetId: volcengine.String("subnet-123"), SecurityGroupIds: volcengine.StringSlice([]string{"sg-123"}), InstanceName: volcengine.String("web-server-1"), }) if err != nil { log.Printf("Failed to create instance: %v", err) return } for _, instance := range resp.Instances { log.Printf("Created instance: %s", volcengine.StringValue(instance.InstanceId)) } ``` -------------------------------- ### Creating a Custom Error Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/07-error-handling.md Example of how to create a custom error using `volcengineerr.New`. ```go import "github.com/volcengine/volcengine-go-sdk/volcengine/volcengineerr" customErr := volcengineerr.New( "CustomErrorCode", "This is a custom error message", nil) log.Println(customErr) ``` -------------------------------- ### Describe Instances Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/08-common-service-patterns.md Example for describing ECS instances by their IDs, showing how to retrieve instance status. ```go resp, err := ecsClient.DescribeInstances(&ecs.DescribeInstancesInput{ InstanceIds: volcengine.StringSlice([]string{"i-123", "i-456"}), }) if err != nil { return } for _, inst := range resp.Instances { log.Printf("Instance: %s, Status: %s", volcengine.StringValue(inst.InstanceId), volcengine.StringValue(inst.Status)) } ``` -------------------------------- ### Create Listener Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/08-common-service-patterns.md Example for creating an HTTP listener for an ALB load balancer. ```go resp, err := albClient.CreateListener(&alb.CreateListenerInput{ LoadBalancerId: volcengine.String("lb-123"), Protocol: volcengine.String("HTTP"), Port: volcengine.Int64(80), ListenerName: volcengine.String("http-listener"), }) if err != nil { return } listenerId := volcengine.StringValue(resp.ListenerId) ``` -------------------------------- ### Tag Operations Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/08-common-service-patterns.md Examples for creating resources with tags and batch tagging resources. ```go // 创建带标签的资源 resp, err := ecsClient.RunInstances(&ecs.RunInstancesInput{ InstanceName: volcengine.String("web-server"), Tags: []*ecs.Tag{ { Key: volcengine.String("Environment"), Value: volcengine.String("Production"), }, { Key: volcengine.String("Team"), Value: volcengine.String("Platform"), }, }, }) // 批量打标签 vpcClient.TagResources(&vpc.TagResourcesInput{ ResourceIds: volcengine.StringSlice([]string{"vpc-123", "vpc-456"}), ResourceType: volcengine.String("vpc"), Tags: volcengine.StringMap(map[string]string{ "Environment": "Production", "CostCenter": "12345", }), }) ``` -------------------------------- ### Create Session with Proxy Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/02-session-reference.md Example of creating a session with an HTTP proxy configured. ```go sess, err := session.NewSession(volcengine.NewConfig(). WithRegion("cn-beijing"). WithAkSk("ak", "sk"). WithHTTPProxy("http://proxy.example.com:8080")) if err != nil { panic(err) } ``` -------------------------------- ### Batch Operations Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/QUICK-REFERENCE.md Examples of performing batch operations, such as creating security group rules or terminating instances. ```go // 批量创建规则 vpcClient.CreateSecurityGroupRules(&vpc.CreateSecurityGroupRulesInput{ SecurityGroupId: volcengine.String("sg-123"), SecurityGroupRules: []*vpc.SecurityGroupRule{ // ... 多个规则 }, }) // 批量删除实例 ecsClient.TerminateInstances(&ecs.TerminateInstancesInput{ InstanceIds: volcengine.StringSlice([]string{"i-1", "i-2", "i-3"}), }) ``` -------------------------------- ### Create Scaling Policy Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/08-common-service-patterns.md Example for creating a target tracking scaling policy. ```go resp, err := asClient.CreateScalingPolicy(&autoscaling.CreateScalingPolicyInput{ AutoScalingGroupId: volcengine.String("asg-123"), PolicyName: volcengine.String("cpu-scale-up"), PolicyType: volcengine.String("TargetTrackingScaling"), TargetTrackingScalingPolicyConfiguration: &autoscaling.TargetTrackingScalingPolicyConfiguration{ TargetValue: volcengine.Float64(70.0), PredefinedMetricSpecification: &autoscaling.PredefinedMetricSpecification{ PredefinedMetricType: volcengine.String("CPUUtilization"), }, }, }) ``` -------------------------------- ### HTTP(S) Proxy Configuration Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/docs/3-Transport-zh.md Example demonstrating how to configure HTTP and HTTPS proxies using WithHTTPProxy and WithHTTPSProxy. ```go var ak, sk, region string config = volcengine.NewConfig(). WithCredentials(credentials.NewStaticCredentials(ak, sk, "")). WithRegion(region).WithHTTPProxy("http://your_proxy:8080").WithHTTPSProxy("http://your_proxy:8080") sess, _ = session.NewSession(config) client = ecs.New(sess) ``` -------------------------------- ### Create Session with Custom Logger Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/02-session-reference.md Example of creating a session with a custom logger and log level. ```go logger := volcengine.NewDefaultLogger() sess, err := session.NewSession(volcengine.NewConfig(). WithRegion("cn-beijing"). WithAkSk("ak", "sk"). WithLogger(logger). WithLogLevel(volcengine.LogDebug)) if err != nil { panic(err) } ``` -------------------------------- ### Setting Optional Tags Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/04-types-and-utilities.md Example of setting optional tags for a resource, using a map and a helper function. ```go tags := map[string]string{ "Environment": "Prod", "Owner": "TeamA", } resp, err := ecsClient.CreateInstance(&ecs.CreateInstanceInput{ Tags: volcengine.StringMap(tags), }) ``` -------------------------------- ### CLI Config Credential Provider Example Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/docs/1-Credentials.md This code snippet demonstrates how to use the CliProvider to read credentials from the volcengine-cli config file. It shows how to use the default config path and profile, and how to specify a profile. ```go package main import ( "github.com/volcengine/volcengine-go-sdk/volcengine" "github.com/volcengine/volcengine-go-sdk/volcengine/credentials/clicreds" "github.com/volcengine/volcengine-go-sdk/volcengine/session" ) func main() { // Use default config path and profile config := volcengine.NewConfig(). WithRegion("cn-beijing"). WithCredentials(clicreds.NewCliCredentials("", "")) // Or specify a profile // WithCredentials(clicreds.NewCliCredentials("", "prod")) sess, err := session.NewSession(config) if err != nil { panic(err) } } ``` -------------------------------- ### Adding a Custom Handler Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/09-request-response-handling.md Example of how to create and add a custom handler to the 'Build' phase of the request processing chain. ```go import "github.com/volcengine/volcengine-go-sdk/volcengine/request" // 创建自定义处理器 customHandler := func(req *request.Request) { log.Printf("Processing request: %s %s", req.Operation.HTTPMethod, req.Operation.HTTPPath) if req.HTTPRequest != nil { log.Printf("Request URL: %s", req.HTTPRequest.URL) } } // 获取会话的处理器 sess, _ := session.NewSession(config) client := vpc.New(sess) // 添加处理器(在客户端创建后) client.Handlers.Build.PushBackNamed("CustomHandler", customHandler) ``` -------------------------------- ### Proxy Configuration Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/QUICK-REFERENCE.md Sets up HTTP or HTTPS proxy for SDK requests. ```go // HTTP 代理 config := volcengine.NewConfig(). WithHTTPProxy("http://proxy.example.com:8080") // HTTPS 代理 config := volcengine.NewConfig(). WithHTTPSProxy("http://proxy.example.com:8080") ``` -------------------------------- ### 常用配置 Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/QUICK-REFERENCE.md Common configuration options for the Volcengine SDK. ```go config := volcengine.NewConfig(). WithRegion("cn-beijing"). // 必须 WithAkSk("ak", "sk"). // 凭证方式之一 WithEndpoint("vpc.cn-beijing..."). // 可选 WithMaxRetries(3). // 重试次数 WithLogger(volcengine.NewDefaultLogger()). // 日志 WithLogLevel(volcengine.LogDebug). // 日志级别 WithDebug(true). // 启用调试 WithHTTPProxy("http://proxy:8080"). // 代理 WithDisableSSL(false) // 禁用 SSL(仅测试) ``` -------------------------------- ### 常用环境变量 Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/QUICK-REFERENCE.md Common environment variables for configuring the Volcengine SDK. ```bash # 凭证 export VOLCENGINE_ACCESS_KEY="your-ak" export VOLCENGINE_SECRET_KEY="your-sk" export VOLCENGINE_SESSION_TOKEN="token" # 区域 export VOLCENGINE_REGION="cn-beijing" # 配置 export volcengine_SDK_LOAD_CONFIG="true" export volcengine_PROFILE="default" ``` -------------------------------- ### Automatic Endpoint Resolution Code Example Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/docs/2-Endpoint.md Code example demonstrating automatic endpoint resolution with custom bootstrap regions and DualStack enabled. ```go func main() { regionId := "cn-beijing" config := volcengine.NewConfig(). WithCredentials(credentials.NewEnvCredentials()). WithRegion(regionId). WithUseDualStack(true). WithBootstrapRegion(map[string]struct{}{ "custom_example_region1": {}, "custom_example_region2": {}, }) sess, err := session.NewSession(config) if err != nil { panic(err) } } ``` -------------------------------- ### Get 方法 Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/03-credentials-reference.md 获取当前凭证值。若凭证已过期,则调用提供者重新获取。 ```go func (c *Credentials) Get() (Value, error) ``` ```go credValue, err := credManager.Get() if err != nil { log.Printf("Failed to get credentials: %v", err) return } ``` -------------------------------- ### Custom HTTP Client Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/QUICK-REFERENCE.md Shows how to configure a custom HTTP client with specific transport settings. ```go import ( "net" "net/http" "time" ) transport := &http.Transport{ DialContext: (&net.Dialer{ Timeout: 5 * time.Second, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, } httpClient := &http.Client{ Transport: transport, Timeout: 30 * time.Second, } config := volcengine.NewConfig(). WithHTTPClient(httpClient) ``` -------------------------------- ### Tag Operations Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/QUICK-REFERENCE.md Illustrates how to create resources with tags and perform batch tagging. ```go // 创建带标签的资源 ecsClient.RunInstances(&ecs.RunInstancesInput{ InstanceName: volcengine.String("web-1"), Tags: []*ecs.Tag{ { Key: volcengine.String("Environment"), Value: volcengine.String("Production"), }, }, }) // 批量打标签 vpcClient.TagResources(&vpc.TagResourcesInput{ ResourceIds: volcengine.StringSlice([]string{"vpc-1", "vpc-2"}), ResourceType: volcengine.String("vpc"), Tags: volcengine.StringMap(map[string]string{ "Environment": "Prod", }), }) ``` -------------------------------- ### Expire 方法 Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/03-credentials-reference.md 手动标记凭证为已过期。下一次 Get() 调用时会重新获取凭证。 ```go func (c *Credentials) Expire() ``` ```go // 主动过期凭证并刷新 credManager.Expire() creds, _ := credManager.Get() ``` -------------------------------- ### Delete Resource Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/06-client-reference.md Example of deleting a VPC resource. ```go _ , err := vpcClient.DeleteVpc(&vpc.DeleteVpcInput{ VpcId: volcengine.String("vpc-123"), }) if err != nil { log.Printf("Failed to delete VPC: %v", err) } ``` -------------------------------- ### Modify Resource Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/06-client-reference.md Example of modifying attributes of an existing VPC resource. ```go resp, err := vpcClient.ModifyVpcAttributes(&vpc.ModifyVpcAttributesInput{ VpcId: volcengine.String("vpc-123"), VpcName: volcengine.String("new-name"), }) ``` -------------------------------- ### Delete VPC Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/08-common-service-patterns.md Example for deleting a VPC by its ID. ```go _, err := vpcClient.DeleteVpc(&vpc.DeleteVpcInput{ VpcId: volcengine.String("vpc-123"), }) if err != nil { log.Printf("Failed to delete VPC: %v", err) return } log.Println("VPC deleted successfully") ``` -------------------------------- ### Pagination Mode Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/QUICK-REFERENCE.md Demonstrates how to paginate through results when fetching data, such as VPCs. ```go var pageNum int64 = 1 for { resp, err := client.DescribeVpcs(&vpc.DescribeVpcsInput{ PageNumber: volcengine.Int64(pageNum), PageSize: volcengine.Int64(20), }) if err != nil { break } // 处理 resp.Vpcs if !volcengine.BoolValue(resp.HasMore) { break } pageNum++ } ``` -------------------------------- ### Service Client Creation Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/08-common-service-patterns.md Demonstrates the standard pattern for initializing a service client, including configuration, session creation, and client instantiation. ```go import ( "github.com/volcengine/volcengine-go-sdk/service/{service}" "github.com/volcengine/volcengine-go-sdk/volcengine" "github.com/volcengine/volcengine-go-sdk/volcengine/credentials" "github.com/volcengine/volcengine-go-sdk/volcengine/session" ) func main() { // 1. Create configuration config := volcengine.NewConfig(). WithRegion("cn-beijing"). WithAkSk("your-ak", "your-sk") // 2. Create session sess, err := session.NewSession(config) if err != nil { panic(err) } // 3. Create service client client := {service}.New(sess) // 4. Call API } ``` -------------------------------- ### Logging to File Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/QUICK-REFERENCE.md Configures the SDK logger to output logs to a file. ```go import "os" file, _ := os.Create("sdk.log") defer file.Close() logger := volcengine.NewDefaultLogger() logger.SetIoWriter(file) config := volcengine.NewConfig(). WithLogger(logger). WithLogLevel(volcengine.LogDebugAll) ``` -------------------------------- ### Custom RegionId Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/docs/2-Endpoint.md Example of configuring a custom region ID for the SDK. ```go func main() { regionId := "cn-beijing" config := volcengine.NewConfig(). WithCredentials(credentials.NewEnvCredentials()). WithRegion(regionId) sess, err := session.NewSession(config) if err != nil { panic(err) } } ``` -------------------------------- ### Using Environment Variables Credentials Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/03-credentials-reference.md This code snippet shows how to use credentials provided through environment variables. ```go os.Setenv("VOLCENGINE_ACCESS_KEY", "your-ak") os.Setenv("VOLCENGINE_SECRET_KEY", "your-sk") provider := credentials.NewEnvCredentials() creds := credentials.NewCredentials(provider) config := volcengine.NewConfig(). WithRegion("cn-beijing"). WithCredentials(creds) ``` -------------------------------- ### Register Targets Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/08-common-service-patterns.md Example for registering targets to an ALB target group. ```go _, err := albClient.RegisterTargets(&alb.RegisterTargetsInput{ TargetGroupId: volcengine.String("tg-123"), Targets: []*alb.Target{ { Id: volcengine.String("i-123"), Port: volcengine.Int64(80), Weight: volcengine.Int64(100), }, { Id: volcengine.String("i-456"), Port: volcengine.Int64(80), Weight: volcengine.Int64(100), }, }, }) ``` -------------------------------- ### Create Target Group Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/08-common-service-patterns.md Example for creating a target group for ALB. ```go resp, err := albClient.CreateTargetGroup(&alb.CreateTargetGroupInput{ TargetGroupName: volcengine.String("web-targets"), Protocol: volcengine.String("HTTP"), Port: volcengine.Int64(80), VpcId: volcengine.String("vpc-123"), }) if err != nil { return } tgId := volcengine.StringValue(resp.TargetGroupId) ``` -------------------------------- ### SeekerLen function Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/04-types-and-utilities.md Gets the number of remaining bytes in a Seeker. ```go func SeekerLen(s io.Seeker) (int64, error) ``` -------------------------------- ### Using Default Credentials Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/03-credentials-reference.md This code snippet demonstrates how to obtain default credentials using the `credentials.NewDefaultCredentials()` function. ```go creds, err := credentials.NewDefaultCredentials() if err != nil { panic(err) } config := volcengine.NewConfig(). WithRegion("cn-beijing"). WithCredentials(creds) sess, _ := session.NewSession(config) ``` -------------------------------- ### 常用错误处理 Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/QUICK-REFERENCE.md Common error handling patterns for Volcengine SDK API calls. ```go resp, err := client.DescribeVpcs(input) if err != nil { if aerr, ok := err.(volcengine.Error); ok { switch aerr.Code() { case "InvalidParameter": // 参数错误 case "Unauthorized": // 认证失败 case "NotFound": // 资源不存在 case "ServiceUnavailable": // 服务暂时不可用 } } } ``` -------------------------------- ### Create Auto Scaling Group Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/08-common-service-patterns.md Example for creating an auto scaling group. ```go import "github.com/volcengine/volcengine-go-sdk/service/autoscaling" resp, err := asClient.CreateAutoScalingGroup(&autoscaling.CreateAutoScalingGroupInput{ AutoScalingGroupName: volcengine.String("web-asg"), LaunchConfigurationId: volcengine.String("lc-123"), MinSize: volcengine.Int64(1), MaxSize: volcengine.Int64(10), DesiredCapacity: volcengine.Int64(3), SubnetIds: volcengine.StringSlice([]string{"subnet-123"}), VpcId: volcengine.String("vpc-123"), }) ``` -------------------------------- ### Copy Method Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/01-config-reference.md Creates a shallow copy of the current configuration, optionally merging other configurations. ```go func (c *Config) Copy(cfgs ...*Config) *Config ``` ```go newConfig := baseConfig.Copy() ``` -------------------------------- ### Modify Instance Attributes Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/08-common-service-patterns.md Example for modifying instance attributes such as name and description. ```go _, err := ecsClient.ModifyInstanceAttributes(&ecs.ModifyInstanceAttributesInput{ InstanceId: volcengine.String("i-123"), InstanceName: volcengine.String("new-name"), Description: volcengine.String("Updated description"), }) ``` -------------------------------- ### 常用日志级别 Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/QUICK-REFERENCE.md Available log levels for the Volcengine SDK. ```go volcengine.LogOff // 关闭日志(默认) volcengine.LogDebug // 启用调试日志 volcengine.LogDebugWithRequest // 记录请求 volcengine.LogDebugWithResponse // 记录响应 volcengine.LogDebugWithRequestBody // 记录请求体 volcengine.LogDebugWithResponseBody // 记录响应体 volcengine.LogDebugAll // 所有调试信息 ``` -------------------------------- ### Modify VPC Attributes Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/08-common-service-patterns.md Example for modifying the attributes of an existing VPC, such as its name. ```go _, err := vpcClient.ModifyVpcAttributes(&vpc.ModifyVpcAttributesInput{ VpcId: volcengine.String("vpc-123"), VpcName: volcengine.String("new-name"), }) if err != nil { log.Printf("Failed to modify VPC: %v", err) return } log.Println("VPC modified successfully") ``` -------------------------------- ### 常用凭证方式 Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/QUICK-REFERENCE.md Common credential authentication methods for the Volcengine SDK. ```go // 静态凭证 credentials.NewStaticCredentials("ak", "sk", "") // 环境变量(需要设置 VOLCENGINE_ACCESS_KEY 等) credentials.NewEnvCredentials() // 默认凭证链 credentials.NewDefaultCredentials() // 凭证链 credentials.NewChainCredentials( credentials.NewEnvCredentials(), credentials.NewStaticCredentials("ak", "sk", ""), ) ``` -------------------------------- ### AssumeRoleOIDC - Using Struct Literal Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/docs/1-Credentials-zh.md Example of configuring OIDC credentials provider using a struct literal. ```go func main() { p := &credentials.OIDCCredentialsProvider{ OIDCTokenFilePath: "/path/to/oidc_token_file", // env: VOLCENGINE_OIDC_TOKEN_FILE(必填) RoleTrn: "Your Role Trn", // env: VOLCENGINE_OIDC_ROLE_TRN(必填) RoleSessionName: "", // env: VOLCENGINE_OIDC_ROLE_SESSION_NAME(可选) Policy: "", // env: VOLCENGINE_OIDC_ROLE_POLICY(可选) Endpoint: "", // env: VOLCENGINE_OIDC_STS_ENDPOINT(可选) DurationSeconds: 3600, // 有效期 MaxRetries: volcengine.Int(3), // 可选:失败时额外重试次数;nil 默认 3,0 表示关闭重试 RetryInterval: 1 * time.Second, // 可选:重试间隔;<= 0 时回退到 1s } config := volcengine.NewConfig(). WithRegion("cn-beijing"). WithCredentials(credentials.NewCredentials(p)) sess, err := session.NewSession(config) if err != nil { panic(err) } svc := vpc.New(sess) resp, err := svc.DescribeVpcs(&vpc.DescribeVpcsInput{}) if err != nil { panic(err) } fmt.Println(resp) } ``` -------------------------------- ### CLI Configuration File Credentials Provider Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/docs/1-Credentials-zh.md Shows how to use the CliProvider to load credentials from the volcengine-cli configuration file. ```go package main import ( "github.com/volcengine/volcengine-go-sdk/volcengine" "github.com/volcengine/volcengine-go-sdk/volcengine/credentials/clicreds" "github.com/volcengine/volcengine-go-sdk/volcengine/session" ) func main() { // 使用默认配置路径和 profile config := volcengine.NewConfig(). WithRegion("cn-beijing"). WithCredentials(clicreds.NewCliCredentials("", "")) // 或者指定 profile // WithCredentials(clicreds.NewCliCredentials("", "prod")) sess, err := session.NewSession(config) if err != nil { panic(err) } } ``` -------------------------------- ### Environment Variable Credentials Provider Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/docs/1-Credentials-zh.md Demonstrates how to use the EnvProvider to load credentials from environment variables. ```go package main import ( "github.com/volcengine/volcengine-go-sdk/volcengine" "github.com/volcengine/volcengine-go-sdk/volcengine/credentials" "github.com/volcengine/volcengine-go-sdk/volcengine/session" ) func main() { config := volcengine.NewConfig(). WithRegion("cn-beijing"). WithCredentials(credentials.NewEnvCredentials()) sess, err := session.NewSession(config) if err != nil { panic(err) } } ``` -------------------------------- ### Enable Request Logging Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/09-request-response-handling.md Shows how to enable request logging by creating a default logger and setting the log level to `LogDebugWithRequest`. ```go config := volcengine.NewConfig(). WithLogger(volcengine.NewDefaultLogger()). WithLogLevel(volcengine.LogDebugWithRequest) ``` -------------------------------- ### WithCredentials Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/_autodocs/01-config-reference.md 设置凭证对象。 ```go func (c *Config) WithCredentials(creds *credentials.Credentials) *Config ``` ```go config.WithCredentials(credentials.NewStaticCredentials("ak", "sk", "")) ```