Initialization
Confirm Endpoint
Before configuring the Endpoint for SDK usage, please refer to the developer guide section on [BOS Access Domain Name](BOS/Developer Guide/Basic concepts.md#Endpoint) to understand Endpoint-related concepts. Baidu AI Cloud currently supports multiple regions. Please refer to[Region Selection Guide](Reference/Region Selection Instructions/Region.md).
Refer to the following link for region and endpoint
https://cloud.baidu.com/doc/BOS/s/akrqd2wcx
Common examples are as follows:
| Access region | Endpoint |
|---|---|
| BJ | bj.bcebos.com |
| BD | bd.bcebos.com |
| SU | su.bcebos.com |
| GZ | gz.bcebos.com |
| CD | cd.bcebos.com |
| HKG | hkg.bcebos.com |
| FWH | fwh.bcebos.com |
| FSH | fsh.bcebos.com |
Retrieve access key
To use Baidu AI Cloud Object Storage (BOS), you need valid AK (Access Key ID) and SK (Secret Access Key) credentials for signature verification. AK/SK are system-assigned strings used to identify users and authenticate BOS requests.
Your AK/SK information can be obtained and understood through the following steps:
Register a Baidu AI Cloud account
Create a new BOS client
A BOS client serves as the interface for BOS services, providing developers with various methods to interact with BOS functionalities.
Create a new BOS client with AK/SK
Users can refer to the following code to create a new BOS Client to access BOS with AK/SK:
1import (
2 "github.com/baidubce/bce-sdk-go/services/bos"
3)
4func main() {
5 // User’s Access Key ID and Secret Access Key
6 AK, SK := <ak>, <sk>
7 // User-specified Endpoint
8 ENDPOINT := <domain-name>
9
10 clientConfig := bos.BosClientConfiguration{
11 Ak: AK,
12 Sk: SK,
13 Endpoint: ENDPOINT,
14 RedirectDisabled: false,
15 }
16 // Initialize a BOSClient
17 bosClient, err := bos.NewClientWithConfig(&clientConfig)
18}
In the code above, AK corresponds to the "Access Key ID" in the console, and SK corresponds to the "Access Key Secret" in the console. For the access method, please refer to the Operation Guide for [Managing Access Key](Reference/Retrieve AK and SK/How to Obtain AKSK.md). The third parameter ENDPOINT is a user-specified domain name. If left empty, the default domain name will be used as the BOS service address.RedirectDisabled: Whether to disable redirection; set to “true” to disable.
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 behttp://bj.bcebos.com.
Create a BOS client with STS
Request STS Token
BOS allows temporary third-party access authorization using the STS mechanism. STS (Security Token Service) is a temporary authorization tool provided by Baidu AI Cloud, enabling you to issue access credentials with customized validity periods and permissions for third-party users. These users can use the credentials to call Baidu AI Cloud APIs or SDKs directly to access cloud resources.
To access BOS via STS, users must first request a certification string through the STS client. For instructions on obtaining STS credentials, refer to [Baidu AI Cloud STS Usage Guide](BOS/API Reference/Access control.md).
Create BOS Client with STS Token
After obtaining the STS credentials, configure the STS Token in the BOS Client to enable the creation of the BOS Client with the token.
Code example
The GO SDK implements the STS service API. Below is a complete example for requesting an STS Token and creating an BOS 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/bos" //Import BOS 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
16 //Obtain a temporary authentication token with a validity period of 60 seconds and an empty ACL
17 sts, err := stsClient.GetSessionToken(60, "")
18 if err != nil {
19 fmt.Println("get session token failed:", err)
20 return
21 }
22
23 //If special permissions need to be specified, the sample code is as follows
24 /*
25 aclstr := `{
26 "accessControlList":[
27 {
28 "region":"*",
29 "effect":"Allow",
30 "resource":["*"],
31 "service":"bce:bos",
32 "permission":["READ", "WRITE"]
33 }
34 ]
35 }`
36 sts, err := stsClient.GetSessionToken(60, aclstr)
37 /*
38 fmt.Println("GetSessionToken result:")
39 fmt.Println(" accessKeyId:", sts.AccessKeyId)
40 fmt.Println(" secretAccessKey:", sts.SecretAccessKey)
41 fmt.Println(" sessionToken:", sts.SessionToken)
42 fmt.Println(" createTime:", sts.CreateTime)
43 fmt.Println(" expiration:", sts.Expiration)
44 fmt.Println(" userId:", sts.UserId)
45 //Create a BOS Client object using the requested temporary STS, with the default endpoint
46 bosClient, err := bos.NewClient(sts.AccessKeyId, sts.SecretAccessKey, "")
47 if err != nil {
48 fmt.Println("create bos client failed:", err)
49 return
50 }
51 stsCredential, err := auth.NewSessionBceCredentials(
52 sts.AccessKeyId,
53 sts.SecretAccessKey,
54 sts.SessionToken)
55 if err != nil {
56 fmt.Println("create sts credential object failed:", err)
57 return
58 }
59 bosClient.Config.Credentials = stsCredential
60}
Note: Currently, when configuring a BOS client with STS, regardless of where the corresponding BOS 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 BOS
BOS supports the HTTPS transport protocol. To use HTTPS to access BOS services with the BOS Go SDK, specify HTTPS in the endpoint when creating the BOS client object.
1// import "github.com/baidubce/bce-sdk-go/services/bos"
2 ENDPOINT := "https://bj.bcebos.com" //Specify the use of HTTPS protocol
3AK, SK := <your-access-key-id>, <your-secret-access-key>
4bosClient, _ := bos.NewClient(AK, SK, ENDPOINT)
Configure custom domain name/backup domain name to access BOS
Use a custom domain name
If you want to use a custom domain name as the endpoint to access BOS, after binding the custom domain name to a BOS bucket in the console, configure the endpoint as the custom domain name and turn on the CnameEnabled switch, such as cdn-test.cdn.bcebos.com. The configuration code is as follows:
1// import "github.com/baidubce/bce-sdk-go/services/bos"
2AK, SK := "xxx", "yyy"
3ENDPOINT := "cdn-test.cdn.bcebos.com"
4bosClient, _ := bos.NewClient(AK, SK, ENDPOINT)
5bosClient.Config.CnameEnabled = true
Use a backup domain name
On the basis of using official domain names and custom domain names as ENDPOINT to access BOS, the SDK further supports the mechanism of retrying the backup domain name when accessing BOS with the ENDPOINT primary domain name fails. The usage method is as follows:
1// If accessing BOS using ENDPOINT fails, the SDK will automatically retry the BackupEndpoint domain name
2bosClient.Config.BackupEndpoint = "cdn-test.bj.bcebos.com"
Configure the BOS client
If users need to configure specific parameters for the BOS Client, they can customize the configuration using the exported Config field of the BOS 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 BOS service using a proxy:
1// import "github.com/baidubce/bce-sdk-go/services/bos"
2 // Create an BOS Client object
3AK, SK := <your-access-key-id>, <your-secret-access-key>
4ENDPOINT := "bj.bcebos.com"
5client, _ := bos.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/bos"
2AK, SK := <your-access-key-id>, <your-secret-access-key>
3ENDPOINT := "bj.bcebos.com"
4client, _ := bos.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/bos"
2AK, SK := <your-access-key-id>, <your-secret-access-key>
3ENDPOINT := "bj.bcebos.com"
4client, _ := bos.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 BOS, the Config field of the created BOS 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
Credentials fieldis created using theauth.NewBceCredentialsandauth.NewSessionBceCredentialsfunctions. The former is used by default, while the latter is used for STS certification. See "Create a BOS client with STS" for details.- 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 Plain Text1Among them, HeadersToSign defaults to `host`, `content-type`, `content-length` and `content-md5`. TimeStamp is generally set to zero, indicating that the timestamp when generating the authentication string is used. Users should not explicitly specify this field’s value. ExpireSeconds defaults to 1,800 seconds (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.
