Route
Initialization
Confirm Endpoint
When confirming the Endpoint configured when you use the SDK, you can first read the section on Route Domain Name in the Developer Guide to understand the Endpoint concept. Baidu Cloud has opened support in multiple regions, please refer to Region Selection Description.
Currently, the six regions are supported: "North China - Beijing", "South China- Guangzhou", "East China - Suzhou", "Hong Kong", "Finance Central China - Wuhan" and "North China - Baoding". The corresponding information is:
Access region | Corresponding 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 |
Get the Key
To use Baidu AI Cloud Route, you need to have a valid AK (Access Key ID) and SK (Secret Access Key) for signature authentication. AK/SK is assigned to users by the system and is a string to identify users and verify signatures for accessing Route.
You can obtain and understand your AK/SK information through the following steps:
[Register Baidu Cloud Account](https://login.bce.baidu.com/reg.html? tpl=bceplat&from=portal)
[Create AK/SK](https://console.bce.baidu.com/iam/? _=1513940574695#/iam/accesslist)
Create New Route Client
Being the client of the Route service, Route Client provides a series of methods for developers to interact with the Route service.
Use AK/SK to Create a New Route Client
Access Route via AK/SK, and users can create a Route Client by reference to the following codes:
import (
"github.com/baidubce/bce-sdk-go/services/vpc"
)
func main() {
// Access Key ID and Secret Access Key of users
ACCESS_KEY_ID, SECRET_ACCESS_KEY := <your-access-key-id>, <your-secret-access-key>
// User specified Endpoint
ENDPOINT := <domain-name>
// Initialize one RouteClient.
routeClient, err := vpc.NewClient(AK, SK, ENDPOINT)
}
In the above code, ACCESS_KEY_ID
corresponds to the "Access Key ID" in the console, and SECRET_ACCESS_KEY
corresponds to the "Access Key Secret" in the console. For how to obtain it, please see How to Get AKSK in the Operation Guide . The third parameter “ENDPOINT” supports the domain name specified by the users themselves, and if it is set as a null string, default domain name is used as the service address of VPC.
Note: The
ENDPOINT
parameter needs to be defined by the domain name of the designated region. If the service region is Beijing, it isbcc.bj.baidubce.com
.
Use STS to Create Route Client
Apply for STS token
Route can implement temporary authorized access by a third party through the STS mechanism. STS (Security Token Service) is a temporary authorization service provided by Baidu Cloud. With STS, you can issue a third-party user with a custom time-based and privileged access credential. Third-party users can use the access credentials to directly call Baidu Cloud's API or SDK to access Baidu Cloud resources.
To access Route through STS, users need to apply for an authentication string through the STS client.
Create a new Route Client with STS token
After STS is applied, STS Token can be configured in Route Client to create Route Client via STS Token.
Code example
GO SDK realizes the interface of STS service, and users can refer to the following complete code to apply for STS Token and create Route Client object.
import (
"fmt"
"github.com/baidubce/bce-sdk-go/auth" // Import authentication module
"github.com/baidubce/bce-sdk-go/services/vpc" // Import VPC service module
"github.com/baidubce/bce-sdk-go/services/sts" // Import STS service module
)
func main() {
// Create the Client object of STS service, with Endpoint of default value
AK, SK := <your-access-key-id>, <your-secret-access-key>
stsClient, err := sts.NewClient(AK, SK)
if err != nil {
fmt.Println("create sts client object :", err)
return
}
// Obtain a temporary authentication token, with a valid period of 60 sec, and ACL null
stsObj, err := stsClient.GetSessionToken(60, "")
if err != nil {
fmt.Println("get session token failed:", err)
return
}
fmt.Println("GetSessionToken result:")
fmt.Println(" accessKeyId:", stsObj.AccessKeyId)
fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey)
fmt.Println(" sessionToken:", stsObj.SessionToken)
fmt.Println(" createTime:", stsObj.CreateTime)
fmt.Println(" expiration:", stsObj.Expiration)
fmt.Println(" userId:", stsObj.UserId)
// Create the Client object of Route service with the temporary STS applied, with Endpoint of default value.
routeClient, err := vpc.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "bcc.bj.baidubce.com")
if err != nil {
fmt.Println("create route client failed:", err)
return
}
stsCredential, err := auth.NewSessionBceCredentials(
stsObj.AccessKeyId,
stsObj.SecretAccessKey,
stsObj.SessionToken)
if err != nil {
fmt.Println("create sts credential object failed:", err)
return
}
routeClient.Config.Credentials = stsCredential
}
Note: Currently, when STS is used to configure Route Client, no matter where the Endpoint of the corresponding Route service is, the Endpoint of STS must be configured as http://sts.bj.baidubce.com. This default value is used to create STS object in the code above.
Configure HTTPS to Access Route
Route supports HTTPS, and you can use HTTPS to access Route service in Route GO SDK by indicating the mode of HTTPS in the Endpoint specified during creation of Route Client object.
// import "github.com/baidubce/bce-sdk-go/services/vpc"
ENDPOINT := "https://bcc.bj.baidubce.com" // Indicate the use of HTTPS
AK, SK := <your-access-key-id>, <your-secret-access-key>
routeClient, _ := vpc.NewClient(AK, SK, ENDPOINT)
Configure Route Client
To configure parameters of some details of Route Client, you can use the export field Config
of Route Client object for custom configuration after creating that object, and can configure agent, maximum connections, etc. for the client.
Use Agent
The following codes enable client to use agent to access Route service:
// import "github.com/baidubce/bce-sdk-go/services/vpc"
// Create RouteClient object
AK, SK := <your-access-key-id>, <your-secret-access-key>
ENDPOINT := "bcc.bj.baidubce.com"
client, _ := vpc.NewClient(AK, SK, ENDPOINT)
// The agent uses the local 8080 port
client.Config.ProxyUrl = "127.0.0.1:8080"
Set Network Parameters
Users can set the network parameters with the following sample code:
// import "github.com/baidubce/bce-sdk-go/services/vpc"
AK, SK := <your-access-key-id>, <your-secret-access-key>
ENDPOINT := "bcc.bj.baidubce.com"
client, _ := bcc.NewClient(AK, SK, ENDPOINT)
// Configuration is not retried, and the default is Back Off retry
client.Config.Retry = bce.NewNoRetryPolicy()
// Configure the connection time-out period as 30sec
client.Config.ConnectionTimeoutInMillis = 30 * 1000
Configure Generation of Signature String Option
// import "github.com/baidubce/bce-sdk-go/services/vpc"
AK, SK := <your-access-key-id>, <your-secret-access-key>
ENDPOINT := "bcc.bj.baidubce.com"
client, _ := bcc.NewClient(AK, SK, ENDPOINT)
// Configure the HTTPS request header for signature as `Host`
headersToSign := map[string]struct{}{"Host": struct{}{}}
client.Config.SignOption.HeadersToSign = HeadersToSign
// Configure the valid period of signature as 30sec
client.Config.SignOption.ExpireSeconds = 30
Parameter Description
When users use GO SDK to access Route, the Config
field of Route Client object created supports all parameters in the table below:
Name of configuration item | Type | Meaning |
---|---|---|
Endpoint | string | Domain name of request service |
ProxyUrl | string | Agent address of client request |
Region | string | Region of request resources |
UserAgent | string | User name, User-Agent header of HTTP request |
Credentials | *auth.BceCredentials | Authentication object of request is classified into ordinary AK/SK and STS |
SignOption | *auth.SignOptions | Signature option of authentication string |
Retry | RetryPolicy | Connection Retry Policy |
ConnectionTimeoutInMillis | int | Connection time-out period, in msec, and the default is 20min |
Note:
Credentials
field is created withauth.NewBceCredentials
andauth.NewSessionBceCredentials
functions, with the former as the default, and the latter used for STS authentication; for details, please see the subsection “Create Route Client with STS”.SignOption
field is the option to generate signature string, for more information, please see the explanation in the table below:
Name | Type | Meaning |
---|---|---|
HeadersToSign | map[string]struct{} | HTTP header used to generate signature string |
Timestamp | int64 | The time stamp used to generate signature string is the value when the request is sent by default. |
ExpireSeconds | int | Valid period of signature string |
Among them, HeadersToSign defaults to `Host`, `Content-Type`, `Content-Length`, `Content-MD5`; TimeStamp is generally zero, indicating the timestamp when the authentication string is generated by the call, and the user should generally not clearly specify the value of this field; ExpireSeconds defaults to 1800 seconds or 30 minutes.
Retry
field specifies the retry strategy, and support 2 retry strategies currently:NoRetryPolicy
andBackOffRetryPolicy
. By default, the latter is used, and this retry strategy specifies the maximum number of retry, longest time of retry and retry base. Retry is performed by multiplying the retry base by exponential growth of 2 until the maximum retry test or the maximum retry time is reached.
Route Table Management
A route table is a list of managed route entries on a router.
Query Route Tables
Complete the query of the route table by the following codes.
//import "github.com/baidubce/bce-sdk-go/services/vpc"
// Method 1: Query by route table id
result, err := client.GetRouteTableDetail(routeTableId, "")
if err != nil {
fmt.Println("get route table error: ", err)
return
}
// Method 2: Query by vpc id
result, err := client.GetRouteTableDetail("", vpcId)
if err != nil {
fmt.Println("get route table error: ", err)
return
}
// Query route table id
fmt.Println("result of route table id: ", result.RouteTableId)
// Query to get vpc id
fmt.Println("result of vpc id: ", result.VpcId)
// Query to get a list of all routroutees
for _, route := range result.RouteRules {
fmt.Println("route rule id: ", route.RouteRuleId)
fmt.Println("route rule routeTableId: ", route.RouteTableId)
fmt.Println("route rule sourceAddress: ", route.SourceAddress)
fmt.Println("route rule destinationAddress: ", route.DestinationAddress)
fmt.Println("route rule nexthopId: ", route.NexthopId)
fmt.Println("route rule nexthopType: ", route.NexthopType)
fmt.Println("route rule description: ", route.Description)
}
Note:
- The request's parameter routeTableId and vpcId cannot be simultaneously empty.
- Use this interface to query a list of all related route rules
Create Route Rules
Use the following codes to create route rules.
//import "github.com/baidubce/bce-sdk-go/services/vpc"
args := &vpc.CreateRouteRuleArgs{
// Set route table id, required
RouteTableId: RouteTableID,
// Set source network segment, required
SourceAddress: "192.168.1.0/24",
// Set the destination network segment, required
DestinationAddress: "172.17.0.0/16",
// Set the next hop type, required
NexthopType: vpc.NEXTHOP_TYPE_NAT,
// Set the next hop id, required
NexthopId: NatID,
// Set the description information of the route rule, optional
Description: "test route rule",
}
result, err := client.CreateRouteRule(args)
if err != nil {
fmt.Println("create route rule error: ", err)
return
}
fmt.Println("create route rule success, route rule id: ", result.RouteRuleId)
To create route table rules, you need to pay attention to the following points:
- When "Custom" is selected for the source segment, the customized segment need to be within the existing subnet range, excluding 0.0.0.0/0;
- The target network and the current VPC cidr cannot overlap (except when the target segment or the VPC cidr is 0.0.0.0/0);
- The source segment and target segment of added route entries cannot be completely consistent with those of existing entries in the route table.
- For the type of the next hop, currently three types are supported: Bcc type is "custom"; VPN type is "vpn"; NAT type is "nat"
Delete Route Rules
Use the following codes to delete specific route rules.
//import "github.com/baidubce/bce-sdk-go/services/vpc"
if err := client.DeleteRouteRule(routeRuleId, clientToken); err != nil {
fmt.Println("delete route rule error: ", err)
return
}
fmt.Printf("delete route rule %s success.", routeRuleId)
Note: The clientToken in the parameter represents an idempotent token, which is an ASCII string no more than 64 bits in length. For details, see ClientToken idempotence