Initialization
Confirm Endpoint
Before configuring the endpoint for SDK usage, please refer toAPI Service Domain Name in API Reference to understand endpoint-related concepts. Baidu AI Cloud currently supports multiple regions. Please refer toRegion Selection Guide. Corresponding information:
| Access region | Endpoint |
|---|---|
| Beijing | eip.bj.baidubce.com |
| Guangzhou | eip.gz.baidubce.com |
| Suzhou | eip.su.baidubce.com |
| Hong Kong | eip.hkg.baidubce.com |
| Wuhan | eip.fwh.baidubce.com |
| Baoding | eip.bd.baidubce.com |
| Shanghai | eip.fsh.baidubce.com |
| Nanjing | eip.nj.baidubce.com |
| Yangquan | eip.yq.baidubce.com |
| Chengdu | eip.cd.baidubce.com |
Retrieve access key
To use Baidu AI Cloud EIP, users need a valid AK (Access Key ID) and SK (Secret Access Key) for signature certification. AK/SK are system-assigned strings used to identify users and perform signature certification for EIP. Your AK/SK information can be obtained and understood through the following steps: Register a Baidu AI Cloud account Create AK/SK
Create a client
Each specific service provides a client object that encapsulates a variety of user-friendly methods for developers to interact with the given service. Developers can explore the SDK directory corresponding to the specific service to access and utilize the relevant functionalities.
Create a new EIP client with AK/SK
Users can refer to the following code to create a new EIP Client to access EIP with AK/SK:
1import (
2 "github.com/baidubce/bce-sdk-go/services/eip"
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 eipClient
10 eipClient, err := eip.NewClient(ACCESS_KEY_ID, SECRET_ACCESS_KEY, ENDPOINT)
11}
Note: The endpoint parameter must correspond to the domain name of the intended region. For example, for a service hosted in Beijing, the endpoint should be defined as http://eip.bj.baidubce.com.
Create a EIP client with STS
Request STS Token
EIP allows temporary third-party access authorization using the STS mechanism. STS (Security Token Service) is a temporary authorization service offered by Baidu AI Cloud. With STS, you can issue access credentials with customizable validity periods and permissions to third-party users. These users can then utilize the credentials to directly call Baidu AI Cloud APIs or SDKs to access cloud resources.
To access EIP through STS, users must first request an authentication string from the STS client.
Create eip Clientwith STS Token
Once the STS token is obtained, it should be configured into the EIP Client to enable its creation based on STS.
Code example
The GO SDK implements the STS service API. Below is a complete example for requesting an STS Token and creating an EIP 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/eip" //Import EIP 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 EIP Client object using the requested temporary STS, defaulted as endpoint
29 eipClient, err := eip.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "eip.bj.baidubce.com")
30 if err != nil {
31 fmt.Println("create eip 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 eipClient.Config.Credentials = stsCredential
43}
Note: When configuring an EIP client with STS, regardless of the location of the corresponding EIP service endpoint, the STS endpoint must always be set to http://sts.bj.baidubce.com. This is the default setting used when creating an STS object in the above code.
Call function API
Developers can use function APIs associated with the created client object of a specific service to take advantage of Baidu AI Cloud's features.
Example
Using Baidu AI Cloud’s EIP as an example, a basic usage case is demonstrated below. For more detailed usage instructions, please refer to the comprehensive documentation for each service.
1import (
2 "github.com/baidubce/bce-sdk-go/services/eip"
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 // EIP service endpoint
8 ENDPOINT := "<domain-name>"
9 // Create EIP service client
10 EIP_CLIENT, _ = NewClient(AK, SK, Endpoint)
11 // Create EIP
12 args := &CreateEipArgs{
13 Name: "sdk-eip",
14 BandWidthInMbps: 1,
15 Billing: &Billing{
16 PaymentTiming: "Postpaid",
17 BillingMethod: "ByTraffic",
18 },
19 ClientToken: getClientToken(),
20 }
21 result, err := EIP_CLIENT.CreateEip(args)
22 if err != nil {
23 fmt.Println("create eip failed:", err)
24 }
25 fmt.Println("create eip success ,eip address is:", result.Eip)
26}
Configuration
Use HTTPS
The SDK supports secure access to Baidu AI Cloud services using HTTPS. To enable HTTPS, simply specify the domain name with HTTPS in the endpoint while creating the client object. The SDK will automatically recognize and use HTTPS for accessing the service.
1// import "github.com/baidubce/bce-sdk-go/services/eip"
2 ENDPOINT := "https://eip.bj.baidubce.com" //Specify the use of HTTPS protocol
3AK, SK := <your-access-key-id>, <your-secret-access-key>
4eipClient, _ := eip.NewClient(AK, SK, ENDPOINT)
Configure the EIP client
If users need to customize specific parameters for the EIP Client, they can modify the exported Config field of the EIP Client object after creating it. This allows for configurations such as proxy settings and maximum connection limits for the client.
Use a proxy
The following code snippet enables the client to access EIP service using a proxy:
1// import "github.com/baidubce/bce-sdk-go/services/eip"
2 // Create an EIP Client object
3AK, SK := <your-access-key-id>, <your-secret-access-key>
4ENDPOINT := "eip.bj.baidubce.com"
5client, _ := eip.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/eip"
2AK, SK := <your-access-key-id>, <your-secret-access-key>
3ENDPOINT := "eip.bj.baidubce.com"
4client, _ := eip.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/eip"
2AK, SK := <your-access-key-id>, <your-secret-access-key>
3ENDPOINT := "eip.bj.baidubce.com"
4client, _ := eip.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
Detailed configurations
When developers use the GO SDK, the client object created for the corresponding service provides the following parameters in its exported Config field for detailed configurations:
| 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 Credentials field is created using the auth.NewBceCredentials and auth.NewSessionBceCredentials functions. The default function is the former, while the latter is used for STS authentication scenarios.
- The SignOption field 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 Retry field defines the retry policy and currently supports two types: NoRetryPolicy and BackOffRetryPolicy. By default, BackOffRetryPolicy is used. This policy specifies the maximum retry attempts, maximum retry duration, and retry base. Retry intervals grow exponentially, using the retry base multiplied by 2, until the maximum attempts or the maximum duration is reached.
1// Client is the `Client` object of a specific service
2 // Configure request proxy address
3client.Config.ProxyUrl = "127.0.0.1:8080"
4 // Configure to not retry, default: Back Off retry
5client.Config.Retry = bce.NewNoRetryPolicy()
6 // Configure connection timeout to 30 seconds
7client.Config.ConnectionTimeoutInMillis = 30 * 1000
8 // Configure the HTTP request header Host for signing
9client.Config.SignOption.HeadersToSign = map[string]struct{}{"Host": struct{}{}}
10 // Configure the validity period of the signature to 30 seconds
11client.Config.SignOption.ExpireSeconds = 30
