VPN
VPN services
Overview
This document details the usage of VPN GO SDK. Prerequisites include prior understanding of VPN fundamentals, and activated VPN service. If you are not yet familiar with VPN, you can refer to Product Description and Guide.
Initialization
Confirm Endpoint
Before configuring the endpoint for SDK usage, please refer to the developer guide section on VPN Service Domain Name to understand endpoint-related concepts. Baidu AI Cloud currently supports multiple regions. Please refer to Region Selection Guide.
Currently supported regions are: "North China-Beijing," "South China-Guangzhou," "East China-Suzhou," "Hong Kong," "Central Finance-Wuhan," and "North China-Baoding." Corresponding details:
| Access region | Endpoint | Protocol |
|---|---|---|
| BJ | bcc.bj.baidubce.com | HTTP and HTTPS |
| GZ | bcc.gz.baidubce.com | HTTP and HTTPS |
| SU | bcc.su.baidubce.com | HTTP and HTTPS |
| HKG | bcc.hkg.baidubce.com | HTTP and HTTPS |
| FWH | bcc.fwh.baidubce.com | HTTP and HTTPS |
| BD | bcc.bd.baidubce.com | HTTP and HTTPS |
Retrieve access key
To use the VPN, users need a valid AK (Access Key ID) and SK (Secret Access Key) for signature verification. AK/SK are system-generated strings used to identify users and perform signature authentication for the VPN.
Your AK/SK information can be obtained and understood through the following steps:
Register a Baidu AI Cloud account
Create a new VPN client
A VPN client acts as the interface for VPN services, offering developers various methods to interact with these services.
Create a new VPN client with AK/SK
Users can refer to the following code to create a new VPN client to access VPN with AK/SK:
1import (
2 "github.com/baidubce/bce-sdk-go/services/vpn"
3)
4func main() {
5 // User’s Access Key ID and Secret Access Key
6 ACCESS_KEY_ID, SECRET_ACCESS_KEY := <your-access-key-id>, <your-secret-access-key>
7 // User-specified Endpoint
8 ENDPOINT := <domain-name>
9 // Initialize a VPNClient
10 vpnClient, err := vpn.NewClient(AK, SK, ENDPOINT)
11}
In the code above, ACCESS_KEY_ID corresponds to “Access Key ID” in the console. SECRET_ACCESS_KEY corresponds to “Access Key Secret” in the console. Refer to the Guide - How to Retrieve AKSK. The third parameter ENDPOINT is a user-specified domain name. If left empty, the default domain name will be used as the VPC service address.
Note:
The endpointparameter must be defined with the domain name of the specified region. For example, if the service is located in Beijing, the endpoint will bebcc.bj.baidubce.com.
Create a VPN client with STS
Request STS Token
VPN allows temporary third-party access authorization through the STS mechanism. STS (Security Token Service) is a temporary authorization service provided by Baidu AI Cloud. Using STS, you can generate access credentials with customized validity and permissions for third-party users. These credentials enable third-party users to directly call Baidu AI Cloud APIs or SDKs to use cloud resources.
To access VPN services via STS, users must first obtain a certification string using the STS client.
Create VPN client with STS token
After acquiring the STS token, configure it in the VPN client to enable creating STS-based VPN clients.
Code example
The GO SDK implements the STS service API. Below is a complete example for requesting an STS token and creating an VPN client object:
1import (
2 "fmt"
3 "github.com/baidubce/bce-sdk-go/auth" //Import the authentication module
4 "github.com/baidubce/bce-sdk-go/services/vpn" //Import VPN service module
5 "github.com/baidubce/bce-sdk-go/services/sts" //Import the Baige service module
6)
7func main() {
8 //Create a Client object for the STS service, using the default Endpoint
9 AK, SK := <your-access-key-id>, <your-secret-access-key>
10 stsClient, err := sts.NewClient(AK, SK)
11 if err != nil {
12 fmt.Println("create sts client object :", err)
13 return
14 }
15 //Obtain a temporary authentication token with a validity period of 60 seconds and an empty ACL
16 stsObj, err := stsClient.GetSessionToken(60, "")
17 if err != nil {
18 fmt.Println("get session token failed:", err)
19 return
20 }
21 fmt.Println("GetSessionToken result:")
22 fmt.Println(" accessKeyId:", stsObj.AccessKeyId)
23 fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey)
24 fmt.Println(" sessionToken:", stsObj.SessionToken)
25 fmt.Println(" createTime:", stsObj.CreateTime)
26 fmt.Println(" expiration:", stsObj.Expiration)
27 fmt.Println(" userId:", stsObj.UserId)
28 //Create a VPN client object using the requested temporary STS, with the default endpoint
29 vpnClient, err := vpn.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "bcc.bj.baidubce.com")
30 if err != nil {
31 fmt.Println("create vpn client failed:", err)
32 return
33 }
34 stsCredential, err := auth.NewSessionBceCredentials(
35 stsObj.AccessKeyId,
36 stsObj.SecretAccessKey,
37 stsObj.SessionToken)
38 if err != nil {
39 fmt.Println("create sts credential object failed:", err)
40 return
41 }
42 vpnClient.Config.Credentials = stsCredential
43}
Note: Currently, when configuring a VPN client with STS, regardless of where the corresponding VPN service endpoint is located, the STS endpoint must be set to http://sts.bj.baidubce.com. This default is utilized when creating an STS object in the above code.
Configure HTTPS access to VPN
VPN supports the HTTPS transport protocol. To use HTTPS to access VPN services with the VPN Go SDK, specify HTTPS in the endpoint when creating the VPN client object.
1// import "github.com/baidubce/bce-sdk-go/services/vpn"
2 ENDPOINT := ""https://bcc.bj.baidubce.com" // Specify the use of HTTPS protocol
3AK, SK := <your-access-key-id>, <your-secret-access-key>
4vpnClient, _ := vpn.NewClient(AK, SK, ENDPOINT)
Configure the VPN client
If users need to configure specific parameters for the VPN client, they can customize the configuration using the exported Config field of the VPN client object after its creation. This allows for configuring parameters such as proxy and maximum number of connections for the client.
Use a proxy
The following code snippet enables the client to access VPN service using a proxy:
1// import "github.com/baidubce/bce-sdk-go/services/vpn"
2 // Create an VPN client object
3AK, SK := <your-access-key-id>, <your-secret-access-key>
4ENDPOINT := "bcc.bj.baidubce.com"
5client, _ := vpn.NewClient(AK, SK, ENDPOINT)
6 // Use the local port 8080 for the proxy
7client.Config.ProxyUrl = "127.0.0.1:8080"
Set network parameters
Users can configure network parameters using the following example code:
1// import "github.com/baidubce/bce-sdk-go/services/vpn"
2AK, SK := <your-access-key-id>, <your-secret-access-key>
3ENDPOINT := "bcc.bj.baidubce.com"
4client, _ := bcc.NewClient(AK, SK, ENDPOINT)
5 // Configure to not retry, default: Back Off retry
6client.Config.Retry = bce.NewNoRetryPolicy()
7 // Configure connection timeout to 30 seconds
8client.Config.ConnectionTimeoutInMillis = 30 * 1000
Configure options for generating signature strings
1// import "github.com/baidubce/bce-sdk-go/services/vpn"
2AK, SK := <your-access-key-id>, <your-secret-access-key>
3ENDPOINT := "bcc.bj.baidubce.com"
4client, _ := bcc.NewClient(AK, SK, ENDPOINT)
5 // Configure the HTTP request header Host for signing
6headersToSign := map[string]struct{}{"Host": struct{}{}}
7client.Config.SignOption.HeadersToSign = HeadersToSign
8 // Configure the validity period of the signature to 30 seconds
9client.Config.SignOption.ExpireSeconds = 30
Parameter description
When using the GO SDK to access VPN, the Config field of the created VPN client object supports the following parameters, as shown in the table below:
| ConfigMap name | Types | Meaning |
|---|---|---|
| Endpoint | string | Domain name for service requests |
| ProxyUrl | string | The proxy address for client requests |
| Region | string | Region for resource requests |
| UserAgent | string | User name, HTTP request’s User-Agent header |
| Credentials | *auth.BceCredentials | Authentication object for requests, divided into regular AK/SK and STS |
| SignOption | *auth.SignOptions | Options for authentication string signing |
| Retry | RetryPolicy | Retry policy for connections |
| ConnectionTimeoutInMillis | int | Connection timeout, in milliseconds, defaulting to 20 minutes |
Description:
- The
Credentialsis created using theauth.NewBceCredentialsandauth.NewSessionBceCredentialsfunctions. The former is used by default, while the latter is used for STS certification. For details, refer to Create a VPC Client with STS. - The
SignOptionfield represents options when generating a signature string, as detailed in the table below:
| Name | Types | Meaning |
|---|---|---|
| HeadersToSign | map[string]struct{} | HTTP headers used when generating the signature string |
| Timestamp | int64 | Timestamp used in the generated signature string, defaulting to the value at the time of sending request |
| ExpireSeconds | int | Validity period of the signature string |
1 Among configuration options, HeadersToSign defaults to `Host`, `Content-Type`, `Content-Length` and `Content-MD5`; TimeStamp is typically set to zero, indicating that the timestamp at the time of generating the certification string shall be used, and users generally shall not explicitly specify the value for this field; ExpireSeconds defaults to 1,800 seconds or 30 minutes.
- The
Retryfield specifies the retry policy, currently supporting two types:NoRetryPolicyandBackOffRetryPolicy. By default, the latter is used. This retry policy specifies the maximum number of retries, the maximum retry duration, and the retry base. Retries increase exponentially based on the retry base multiplied by 2 until the maximum number of retries or the maximum retry duration is reached.
VPN management
Create VPN
Function declaration
1func (c *Client) CreateVpnGateway(args *CreateVpnGatewayArgs) (*CreateVpnGatewayResult, error)
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/tk2y913ko
Response value
Operation succeeded:
1 {
2 "vpnId": "vpn-ku4cxya6nisq"
3 }
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer to example_create_vpn_gateway.go
Query VPN list
Function declaration
1func (c *Client) ListVpnGateway(args *ListVpnGatewayArgs) (*ListVpnGatewayResult, error)
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/zk2ydcivt
Response value
Operation succeeded:
1{
2 "nextMarker": "vpn-xktdeMSf",
3 "marker": "vpn-IyWRtII7",
4 "maxKeys": 1,
5 "isTruncated": true,
6 "vpns": [
7 {
8 "status": "active",
9 "eip": "10.12.34.32",
10 "vpnId": "vpn-IyWRtII7",
11 "vpcId": "83edd0d2-8a68-4ce5-a396-9d2917d58a57",
12 "description": "",
13 "expiredTime": null,
14 "paymentTiming": "Postpaid",
15 "vpnConnNum": 0,
16 "bandwidthInMbps": 10,
17 "vpnConns": [],
18 "vpnName": "VPN_aoko_2",
19 "createTime": "2021-04-25 17:22:34"
20 }
21 ]
22}
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer to example_list_vpn_gateway.go
Query VPN details
Function declaration
1func (c *Client) GetVpnGatewayDetail(vpnId string) (*VPN, error)
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/Xk2ydminh
Response value
Operation succeeded:
1{
2 "status": "active",
3 "eip": "",
4 "vpnId": "vpn-shkgan7et1vx",
5 "vpcId": "83edd0d2-8a68-4ce5-a396-9d2917d58a57",
6 "description": "",
7 "expiredTime": null,
8 "paymentTiming": "Postpaid",
9 "vpnConnNum": 0,
10 "bandwidthInMbps": 0,
11 "vpnConns": [],
12 "vpnName": "VPN_aoko_2",
13 "createTime": "2021-04-25 17:22:34",
14 "deleteProtect": true,
15 "tags": [
16 {
17 "tagKey": "hikwnf",
18 "tagValue": "nwklwmflk"
19 },
20 {
21 "tagKey": "whfooef",
22 "tagValue": "haiwnwejf"
23 }
24 ]
25}
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer to example_get_vpn_gateway_detail.go
Update VPN gateway
Function declaration
1func (c *Client) UpdateVpnGateway(vpnId string, args *UpdateVpnGatewayArgs) error
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/dk2ybo3p4
Response value
Operation succeeded:
1nil
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer to example_update_vpn_gateway.go
Release VPN
Note:
- Release specified VPN; released VPN can nor be recovered
- For early release of prepaid VPNs, please submit a ticket
Function declaration
1func (c *Client) DeleteVpnGateway(vpcId, clientToken string) error
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/bk2ybhrpv
Response value
Operation succeeded:
1nil
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer to example_delete_vpn_gateway.go
Bind EIP
Note:
- The binding of an EIP is an asynchronous process. Users can determine whether the binding is successful by querying the VPN status
Function declaration
1func (c *Client) BindEip(vpnId string, args *BindEipArgs) error
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/uk2yh2wy2
Response value
Operation succeeded:
1nil
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer to example_bind_eip.go
Unbind EIP
Note: The unbinding of an EIP is an asynchronous process. Users can determine whether the binding is successful by querying the VPN status
Function declaration
1func (c *Client) UnBindEip(vpnId, clientToken string) error
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/lk2yh59e5
Response value
Operation succeeded:
1nil
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer to example_unbind_eip.go
VPN gateway renewal
Note:
- Only prepaid resources are eligible for renewal.
Function declaration
1func (c *Client) RenewVpnGateway(vpnId string, args *RenewVpnGatewayArgs) error
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/rk2yh7kqp
Response value
Operation succeeded:
1nil
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer toexample_renew_vpn_gateway.go
Create VPN tunnel
Function declaration
1func (c *Client) CreateVpnConn(args *CreateVpnConnArgs) (*CreateVpnConnResult, error)
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/sk2yngg0t
Response value
Operation succeeded:
1{
2 "secretKey": "ddd22@www",
3 "localSubnets": ["192.168.0.0/20"],
4 "remoteIp": "10.107.245.188",
5 "remoteSubnets": ["192.168.100.0/24"],
6 "description": "111",
7 "vpnConnName": "vpncon",
8 "ikeConfig":
9 {
10 "ikeVersion": "v1",
11 "ikeMode": "main",
12 "ikeEncAlg": "aes",
13 "ikeAuthAlg": "sha1",
14 "ikePfs": "group2",
15 "ikeLifeTime":200
16 },
17 "ipsecConfig":
18 {
19 "ipsecEncAlg": "aes",
20 "ipsecAuthAlg": "sha1",
21 "ipsecPfs": "group2",
22 "ipsecLifetime": 28800
23 }
24}
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer to example_create_vpn_conn.go
Query VPN tunnels
Function declaration
1func (c *Client) ListVpnConn(vpnId string) (*ListVpnConnResult, error)
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/Bk2ynne1n
Response value
Operation succeeded:
1{
2 "vpnConns": [
3 {
4 "vpnId": "vpn-a0314a79a558",
5 "vpnConnId": "vpnconn-771763a0da2f",
6 "localIp": null,
7 "secretKey": "ddd22@www",
8 "localSubnets": ["192.168.100.0/24"],
9 "remoteIp": "10.107.245.188",
10 "remoteSubnets": ["192.168.100.0/24"],
11 "description": "111",
12 "status": "active",
13 "createdTime": "2024-12-26T18:58:53+08:00",
14 "healthStatus": "reachable",
15 "vpnConnName": "vpncon",
16 "ikeConfig":
17 {
18 "ikeVersion": "v1",
19 "ikeMode": "main",
20 "ikeEncAlg": "aes",
21 "ikeAuthAlg": "sha1",
22 "ikePfs": "group2",
23 "ikeLifeTime": "28800s"
24 },
25 "ipsecConfig":
26 {
27 "ipsecEncAlg": "aes",
28 "ipsecAuthAlg": "sha1",
29 "ipsecPfs": "group2",
30 "ipsecLifetime": "28800s"
31 }
32 }
33 ]
34}
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer to example_list_vpn_conn.go
Update VPN tunnel
Function declaration
1func (c *Client) UpdateVpnConn(args *UpdateVpnConnArgs) error
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/rk2ynjopp
Response value
Operation succeeded:
1nil
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer to example_update_vpn_conn.go
Delete VPN tunnel
Function declaration
1func (c *Client) DeleteVpnConn(vpnConnId, clientToken string) error
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/dk2ynpyn7
Response value
Operation succeeded:
1nil
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer to example_delete_vpn_conn.go
Create SSL VPN server
Function declaration
1func (c *Client) CreateSslVpnServer(args *CreateSslVpnServerArgs) (*CreateSslVpnServerResult, error)
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/Jl385fe3r
Response value
Operation succeeded:
1 {
2 "sslVpnServerId": "sslvpn-5b2hq4nm40tt"
3 }
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer to example_create_ssl_vpn_server.go
Query SSL-VPN server
Function declaration
1func (c *Client) GetSslVpnServer(vpnId, clientToken string) (*SslVpnServer, error)
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/vl3bat97z
Response value
Operation succeeded:
1{
2 "vpnId": "vpn-shyt1vzgqc3z",
3 "sslVpnServerId": "sslvpn-5b2hq4nm40tt",
4 "sslVpnServerName": "hzb_1_1",
5 "interfaceType": "tap",
6 "status": "active",
7 "localSubnets": ["192.168.0.0/24"],
8 "remoteSubnet": "172.168.0.0/16",
9 "maxConnection": 10,
10 "clientDns":""
11}
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer to example_get_ssl_vpn_server.go
Update SSL VPN server
Function declaration
1func (c *Client) UpdateSslVpnServer(args *UpdateSslVpnServerArgs) error
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/Gl39u2j5r
Response value
Operation succeeded:
1nil
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer toexample_update_ssl_vpn_server.go
Delete SSL VPN server
Function declaration
1func (c *Client) DeleteSslVpnServer(vpnId, sslVpnServerId, clientToken string) error
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/ll39xiyyp
Response value
Operation succeeded:
1nil
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer toexample_delete_ssl_vpn_server.go
Create SSL VPN users in batches
Function declaration
1func (c *Client) BatchCreateSslVpnUser(args *BatchCreateSslVpnUserArgs) (*BatchCreateSslVpnUserResult, error)
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/Kl3a3l8ga
Response value
Operation succeeded:
1{
2 "sslVpnUserIds": ["sslvpn-5b2hq4nm40tt"]
3}
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer toexample_batch_create_ssl_vpn_user.go
Update SSL VPN user
Function declaration
1func (c *Client) UpdateSslVpnUser(args *UpdateSslVpnUserArgs) error
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/el3b86jjt
Response value
Operation succeeded:
1nil
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer toexample_update_ssl_vpn_user.go
Delete SSL VPN user
Function declaration
1func (c *Client) DeleteSslVpnUser(vpnId, userId, clientToken string) error
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/Wl3b99ax6
Response value
Operation succeeded:
1nil
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer toexample_delete_ssl_vpn_user.go
Query SSL-VPN user
Function declaration
1func (c *Client) ListSslVpnUser(args *ListSslVpnUserArgs) (*ListSslVpnUserResult, error)
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/Sl3b9pzmg
Response value
Operation succeeded:
1{
2 "marker": "vpn-ssl-user-xynkefqf3n5x",
3 "maxKeys": 1,
4 "isTruncated": false,
5 "sslVpnUsers": [
6 {
7 "userId": "vpn-ssl-user-xynkefqf3n5x",
8 "userName": "user",
9 "description": "desc"
10 }
11 ]
12}
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer toexample_list_ssl_vpn_user.go
Update VPN release protection switch
Function declaration
1func (c *Client) UpdateVpnDeleteProtect(args *UpdateVpnDeleteProtectArgs) error
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/Dlzjsmzon
Response value
Operation succeeded:
1nil
Operation failed: An error is returned, for details, refer to [Error handling](#Error handling) section.
Example code
For specific code examples, refer to example_update_vpn_delete_protect.go
Error handling
The Go language uses the error type to identify errors. VPN supports two types of errors as shown in the table below:
| Error type | Description |
|---|---|
| BceClientError | Errors caused by user operations |
| BceServiceError | Errors returned by the VPN service |
When calling VPN-related APIs using the SDK, besides returning the required results, errors might also be returned. Users can retrieve and handle these errors. An example is as follows:
1// vpnClient is the created VPN client object
2args := &vpn.ListVpnGatewayArgs{}
3result, err := client.ListVpnGateway(args)
4if err != nil {
5 switch realErr := err.(type) {
6 case *bce.BceClientError:
7 fmt.Println("client occurs error:", realErr.Error())
8 case *bce.BceServiceError:
9 fmt.Println("service occurs error:", realErr.Error())
10 default:
11 fmt.Println("unknown error:", err)
12 }
13}
Client exception
Client exceptions occur when the client faces issues while sending requests or transmitting data to the VPN. For instance, if the network connection is unavailable during a request, a BceClientError will be returned.
Server exception
A server exception is generated when VPN server-side errors occur. The service returns detailed error messages to assist troubleshooting. For common server exceptions, refer to VPN Error Code
SDK logging
The VPN GO SDK has a logging module that supports six levels, three output destinations (standard output, standard error, file), and basic format settings. Its import path is github.com/baidubce/bce-sdk-go/util/log. When outputting to a file, it supports setting five log rolling modes (no rolling, rolling by day, rolling by hour, rolling by minute, rolling by size). In this case, the directory for output log files also needs to be set.
Default logging
The VPN GO SDK itself uses a package-level global log object, which does not record logs by default. If users need to output SDK-related logs, users must specify the output method and level by themselves. For details, refer to the following examples:
1// import "github.com/baidubce/bce-sdk-go/util/log"
2 // Specify output to standard error, output INFO and above levels
3log.SetLogHandler(log.STDERR)
4log.SetLogLevel(log.INFO)
5 // Specify output to standard error and file, DEBUG and above levels, rolling by 1 GB file size
6log.SetLogHandler(log.STDERR | log.FILE)
7log.SetLogDir("/tmp/gosdk-log")
8log.SetRotateType(log.ROTATE_SIZE)
9log.SetRotateSize(1 << 30)
10 // Output to standard output, only output level and log message
11log.SetLogHandler(log.STDOUT)
12log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG})
Description:
- The default log output level is
DEBUG - If set to output to a file, the default log output directory is
/tmp, and it rolls by hour by default - If set to output to a file and roll by size, the default rolling size is 1 GB
- The default log output format is:
FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG
Project usage
This logging module has no external dependencies. When users develop projects using the GO SDK, they can directly reference this logging module for use in their projects. Users can continue to use the package-level log object used by the GO SDK or create new log objects. See the following examples for details:
1// Directly use the package-level global log object (will be output together with the GO SDK’s own logs)
2log.SetLogHandler(log.STDERR)
3log.Debugf("%s", "logging message using the log package in the VPN go sdk")
4 // Create a new log object (output logs according to custom settings, separated from the GO SDK’s log output)
5myLogger := log.NewLogger()
6myLogger.SetLogHandler(log.FILE)
7myLogger.SetLogDir("/home/log")
8myLogger.SetRotateType(log.ROTATE_SIZE)
9myLogger.Info("this is my own logger from the VPN go sdk")
