Help Center/ Object Storage Service/ SDK Reference/ Go/ Getting Started with OBS SDK for Go
Updated on 2024-09-05 GMT+08:00

Getting Started with OBS SDK for Go

Preparing Access Keys

OBS employs access keys (AK and SK) for signature verification to ensure that only authorized accounts can access specified OBS resources. Detailed explanations of access keys are as follows:

  • AK is short for Access Key ID. One AK maps to only one user but one user can have multiple AKs. OBS authenticates users by their AKs.
  • SK is short for Secret Access Key, which is used to access OBS. You can generate authentication information based on SKs and request headers. An SK maps to an AK, and they group into a pair.

Access keys are permanent. There are also temporary security credentials (consisting of an AK/SK pair and a security token). Each user can create a maximum of two valid AK/SK pairs. Temporary security credentials can only be used to access OBS within the specified validity period. Once they expire, they must be requested again. For security purposes, you are advised to use temporary security credentials to access OBS. If you want to use permanent access keys, periodically update them.

  1. Log in to the management console.
  2. In the upper right corner, hover your cursor over the username and choose My Credentials.
  3. On the My Credentials page, click Access Keys in the navigation pane.
  4. On the Access Keys page, click Create Access Key.

    Each user can create a maximum of two valid AK/SK pairs.

  5. In the Create Access Key dialog box, enter a description (recommended), and click OK.

  6. (Optional) In the displayed Identity Verification dialog box, select a verification method, enter the verification code, and click OK.

  7. In the displayed dialog box, click Download to save the access keys to your browser's default download path.

  8. Open the downloaded file credentials.csv to obtain the AK and SK.
  • In the credentials.csv file, the AK is the value in the Access Key ID column, and the SK is the one in the Secret Access Key column.
  • Keep the access keys properly to prevent information leakage. If you click Cancel in the download dialog box, the access keys will not be downloaded and cannot be downloaded later. You can create new access keys if required.

Initializing an obsClient Instance

Each time you want to send an HTTP or HTTPS request to OBS, you must create an ObsClient struct first. Sample code is as follows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Import the dependency package.
import (
    obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)

func main() {
    //Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
    //Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/eu/usermanual-ca/ca_01_0003.html.
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // (Optional) If you use a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding to reduce leakage risks. You can obtain an AK/SK pair using environment variables or import it in other ways.
    // securityToken := os.Getenv("SecurityToken")
    // Enter the endpoint corresponding to the bucket. EU-Dublin is used here as an example. Replace it with the one currently in use.
    endPoint := "https://obs.eu-west-101.myhuaweicloud.eu"
    // Create an obsClient instance.
    // If you use a temporary AK/SK pair and a security token to access OBS, use the obs.WithSecurityToken method to specify a security token when creating an instance.
    obsClient, err := obs.New(ak, sk, endPoint, obs.WithSignature(obs.SignatureObs)/*, obs.WithSecurityToken(securityToken)*/)
    if err == nil {
        // Use the obsClient to access OBS.

        // Close the obsClient.
        obsClient.Close()
    }
}
  • For more information, see section "Initializing OBS SDK for Go."
  • To learn log configuration, see Log Initialization (SDK for Go).
  • If the endpoint you specified does not contain a protocol, HTTPS is used by default.
  • For the sake of high DNS resolution performance and OBS reliability, you can set endpoint only to an OBS domain name, instead of an IP address.

Creating a Bucket

A bucket is a global namespace of OBS. It is a container for storing objects and functions as a root directory of a file system.

This example creates a bucket named examplebucket. For bucket details, see the code comments below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main

import (
    "fmt"
    "os"
    obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)

func main() {
    //Obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways. Using hard coding may result in leakage.
    //Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/eu/usermanual-ca/ca_01_0003.html.
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // (Optional) If you use a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding to reduce leakage risks. You can obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways.
    // securityToken := os.Getenv("SecurityToken")
    // Enter the endpoint corresponding to the region where the bucket is to be created. EU-Dublin is used here as an example. Replace it with the one currently in use.
    endPoint := "https://obs.eu-west-101.myhuaweicloud.eu"
    // Create an obsClient instance.
    // If you use a temporary AK/SK pair and a security token to access OBS, use the obs.WithSecurityToken method to specify a security token when creating an instance.
    obsClient, err := obs.New(ak, sk, endPoint/*, obs.WithSecurityToken(securityToken)*/)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.CreateBucketInput{}
    // Specify a bucket name.
    input.Bucket = "examplebucket"
    // Specify the region where the bucket is to be created. The region must be the same as that in the endpoint passed. eu-west-101 is used as an example.
    input.Location = "eu-west-101"
    // Specify an access control policy for the bucket. obs.AclPrivate is used as an example.
    input.ACL = obs.AclPrivate
    // Specify a storage class for the bucket. obs.StorageClassWarm is used as an example. If this parameter is not specified, the created bucket is in the Standard storage class.
    input.StorageClass = obs.StorageClassWarm
    // Specify the AZ type for the bucket. 3az is used as an example. If the bucket region does not support multi-AZ storage, single-AZ storage will be applied. If this parameter is not specified, single-AZ storage is used by default.
    input.AvailableZone = "3az"
   // Create a bucket.
    output, err := obsClient.CreateBucket(input)
    if err == nil {
        fmt.Printf("Create bucket:%s successful!\n", input.Bucket)
        fmt.Printf("RequestId:%s\n", output.RequestId)
        return
    }
    fmt.Printf("Create bucket:%s fail!\n", input.Bucket)
    if obsError, ok := err.(obs.ObsError); ok {
        fmt.Println("An ObsError was found, which means your request sent to OBS was rejected with an error response.")
        fmt.Println(obsError.Error())
    } else {
        fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
        fmt.Println(err)
    }
}
  • A bucket name must be unique across all accounts and regions.
  • A bucket name:
    • Must be 3 to 63 characters long and start with a digit or letter. Lowercase letters, digits, hyphens (-), and periods (.) are allowed.
    • Cannot be formatted as an IP address.
    • Cannot start or end with a hyphen (-) or period (.).
    • Cannot contain two consecutive periods (..), for example, my..bucket.
    • Cannot contain a period (.) and a hyphen (-) adjacent to each other, for example, my-.bucket or my.-bucket.
  • If you repeatedly create buckets of the same name, no error will be reported and the bucket attributes comply with those specified in the first creation request.
  • For more information, see Creating a Bucket (SDK for Go).

Uploading an Object

After creating a bucket, you can upload objects to it.

This example uploads localfile to examplebucket as an object named example/objectname.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main
import (
    "fmt"
    "os"
    obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)
func main() {
    //Obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways. Using hard coding may result in leakage.
    //Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/eu/usermanual-ca/ca_01_0003.html.
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // (Optional) If you use a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding to reduce leakage risks. You can obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways.
    securityToken := os.Getenv("SecurityToken")
    // Enter the endpoint corresponding to the bucket. EU-Dublin is used here as an example. Replace it with the one currently in use.
    endPoint := "https://obs.eu-west-101.myhuaweicloud.eu" 
    // Create an obsClient instance.
    // If you use a temporary AK/SK pair and a security token to access OBS, use the obs.WithSecurityToken method to specify a security token when creating an instance.
    obsClient, err := obs.New(ak, sk, endPoint, obs.WithSecurityToken(securityToken))
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.PutFileInput{}
    // Specify a bucket name.
    input.Bucket = "examplebucket"
    // Specify the object (example/objectname as an example) to upload.
    input.Key = "example/objectname"
    // Specify a local file (localfile as an example).
    input.SourceFile = "localfile"
    // Perform the file-based upload.
    output, err := obsClient.PutFile(input)
    if err == nil {
        fmt.Printf("Put file(%s) under the bucket(%s) successful!\n", input.Key, input.Bucket)
        fmt.Printf("StorageClass:%s, ETag:%s\n",
            output.StorageClass, output.ETag)
        return
    }
    fmt.Printf("Put file(%s) under the bucket(%s) fail!\n", input.Key, input.Bucket)
    if obsError, ok := err.(obs.ObsError); ok {
        fmt.Println("An ObsError was found, which means your request sent to OBS was rejected with an error response.")
        fmt.Println(obsError.Error())
    } else {
        fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
        fmt.Println(err)
    }
}

For more information, see Object Upload Overview (SDK for Go).