Initialization
Confirm Endpoint
When confirming the Endpoint configured when using SDK, you can read the part in API reference regarding API service domain name, and understand Endpoint related concept. Baidu AI Cloud enables multi-region support currently, please see the description of Region selection. The corresponding information is:
Access region | Corresponding 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 |
Get the Key
To use Baidu AI Cloud EIP, you need to have a valid AK (Access Key ID) and SK (Secret Access Key) for signature authentication. AK/SK is assigned by the system to users, both of which are strings, used to identify users, and perform signature authentication for accessing EIP. You can obtain and understand your AK/SK information through the following steps: Register Baidu AI Cloud Account [Create AK/SK](https://console.bce.baidu.com/iam/? _=1513940574695#/iam/accesslist)
Create Client
Each specific service has a Client object, which encapsulates a series of easy-to-use methods for developers to interact with the corresponding service. Developers can refer to the documentation in the directory corresponding to the specific service in SDK to use the corresponding service.
Use AK/SK to Create EIP Client
Access EIP via AK/SK, and users can create a EIP Client by reference to the following codes:
import (
"github.com/baidubce/bce-sdk-go/services/eip"
)
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 an eipClient
eipClient, err := eip.NewClient(AK, SK, ENDPOINT)
}
Note:
ENDPOINT
needs to be defined with the domain name of specified region. For example, if the service region is Beijing, the domain name is http://eip.bj.baidubce.com.
Use STS to Create EIP Client
Apply for STS Token
EIP 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 EIP through STS, users need to apply for an authentication string through the STS client first.
Create eip Client with STS Token
After STS is applied, STS Token can be configured in EIP Client to create EIP 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 EIP Client object.
import (
"fmt"
"github.com/baidubce/bce-sdk-go/auth" // Import authentication module
"github.com/baidubce/bce-sdk-go/services/eip" //Import EIP 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 EIP service with the temporary STS applied, with Endpoint of default value.
eipClient, err := eip.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "eip.bj.baidubce.com")
if err != nil {
fmt.Println("create eip 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
}
eipClient.Config.Credentials = stsCredential
}
Note: When STS is used to configure rip Client, no matter where the endpoint of the corresponding EIP service is, the endpoint of STS needs to be configured as http://sts.bj.baidubce.com. This default value is used to create STS object in the code above.
Call Function Interface
Based on the Client object of the corresponding service created, the developer can call the corresponding functional interface and use the functions of Baidu Cloud products.
Example
The following uses Baidu Cloud Elastic IP (EIP) as an example to give a basic usage example. For detailed usage instructions, please refer to the detailed documentation of each service.
import (
"github.com/baidubce/bce-sdk-go/services/eip"
)
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>"
// Endpoint of EIP service
ENDPOINT := "<domain-name>"
// Create Client for EIP service
EIP_CLIENT, _ = NewClient(AK, SK, Endpoint)
// Create EIP
args := &CreateEipArgs{
Name: "sdk-eip",
BandWidthInMbps: 1,
Billing: &Billing{
PaymentTiming: "Postpaid",
BillingMethod: "ByTraffic",
},
ClientToken: getClientToken(),
}
result, err := EIP_CLIENT.CreateEip(args)
if err != nil {
fmt.Println("create eip failed:", err)
}
fmt.Println("create eip success ,eip address is:", result.Eip)
}
Configure
Use HTTPS Protocol
The SDK supports the use of HTTPS protocol to access Baidu Cloud's service products. To use the HTTPS protocol, you only need to specify the domain name using the https protocol in the Endpoint specified when you create the Client object of the corresponding service. SDK will automatically recognize and use the HTTPS protocol for access.
// import "github.com/baidubce/bce-sdk-go/services/eip"
ENDPOINT := "https://eip.bj.baidubce.com" //Specify the use of HTTPS protocol
AK, SK := <your-access-key-id>, <your-secret-access-key>
eipClient, _ := eip.NewClient(AK, SK, ENDPOINT)
Configure EIP Client
To configure parameters of some details of EIP Client, you can use the export field Config of EIP 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 the client to access to EIP service with agent.
// import "github.com/baidubce/bce-sdk-go/services/eip"
// Create EIP Client object
AK, SK := <your-access-key-id>, <your-secret-access-key>
ENDPOINT := "eip.bj.baidubce.com"
client, _ := eip.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/eip"
AK, SK := <your-access-key-id>, <your-secret-access-key>
ENDPOINT := "eip.bj.baidubce.com"
client, _ := eip.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/eip"
AK, SK := <your-access-key-id>, <your-secret-access-key>
ENDPOINT := "eip.bj.baidubce.com"
client, _ := eip.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
Detailed Configuration
When developers use GO SDK, the export field Config of the Client object created corresponding to the service provides the following parameters to support detailed configuration:
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:
- The Credentials field is created using the auth.NewBceCredentials and auth. NewSessionBceCredentials functions, the former is used by default, and the latter is used when STS authentication is used.
- 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 and BackOffRetryPolicy. 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.
// Client is a `Client` object for a specific service
// Configure the request proxy address
client.Config.ProxyUrl = "127.0.0.1:8080"
// 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 the HTTPS request header for signature as `Host`
client.Config.SignOption.HeadersToSign = map[string]struct{}{"Host": struct{}{}}
// Configure the valid period of signature as 30sec
client.Config.SignOption.ExpireSeconds = 30