Updated on 2025-10-21 GMT+08:00

Upload Callback (Go SDK)

Function

You can specify the callback parameters in an object upload request. After the object is successfully uploaded, OBS calls back the upload result to a specific server and returns the callback result to you.

If the callback succeeds, a result is returned to the client, with the ETag of the uploaded object returned as the header field. If the callback result also contains the ETag, the ETags will be combined and then returned.

If the callback fails, status code 203 will be returned, indicating that the object is successfully uploaded but the callback fails.

Restrictions

  • To upload an object, you must be the bucket owner or have the required permission (obs:object:PutObject in IAM or PutObject in a bucket policy). For details, see Introduction to OBS Access Control, IAM Custom Policies, and Configuring an Object Policy.
  • To learn about the mappings between OBS regions and endpoints, see Regions and Endpoints.
  • If the size of an uploaded image exceeds 25 MB, the basic image information cannot be obtained using the magic variables related to imageInfo. As a result, the callback fails.
  • To enable upload callbacks, you need to configure the SDK using the WithCallbackHeader method. This method is currently supported only for the APIs of streaming uploads, file-based uploads, and resumable uploads.

Method

WithCallbackHeader(callback string)

Request Parameters

Table 1 List of request parameters

Parameter

Type

Mandatory (Yes/No)

Description

calllback

string

Yes

Explanation:

Upload callback policy

Restrictions:

The value must be a Base64-encoded JSON string. For details about the callback parameters included in the JSON string, see Table 2.

Default value:

None

Table 2 Callback parameters

Parameter

Type

Mandatory (Yes/No)

Description

callbackUrl

string

Yes

Explanation:

After an object is uploaded successfully, OBS sends a callback request to the URL using the POST method.

Restrictions:

  • URL-encoding is required. For example, http://www.example.com/Chinese?key=Chinese name should be encoded into http://www.example.com/%E4%B8%AD%E6%96%87?key=%E4%B8%AD%E6%96%87%E5%90%8D.
  • You can specify a maximum of 10 URLs. Use semicolons (;) to separate URLs.

Default value:

None

callbackHost

string

No

Explanation:

Value of the Host header in the callback request.

Default value:

None. The value of Host parsed from the callbackUrl parameter is used.

callbackBody

string

Yes

Explanation:

Body of the callback request.

Restrictions:

  • The body format must comply with the media type specified in the callbackBodyType field.
  • The callback body supports system variables listed in Table 3. For example, in key=$(key)&hash=$(etag), variables key and etag are system variables. If the object to be uploaded is an image, you can use imageInfo.width and imageInfo.height in the parameter to indicate the width and height of the image. Example: key=$(key)&hash=$(etag)&w=$(imageInfo.width)&h=$(imageInfo.height)

Default value:

None

callbackBodyType

string

No

Explanation:

Value of the Content-Type header in the callback request.

Value range:

  • application/x-www-form-urlencoded
  • application/json

Default value:

application/json

Table 3 System variables supported by the callback body

Variable

Type

Description

fname

string

Name of the original file to be uploaded

fsize

string

Size of the file, in bytes

The name is compatible with size.

etag

string

Object ETag

bucket

string

Name of the bucket to which the object is uploaded

key

string

Explanation:

The name of the uploaded object. An object is uniquely identified by an object name in a bucket. An object name is a complete path that does not contain the bucket name.

For example, if the access path is examplebucket.obs.cn-north-4.ap-southeast-1.myhuaweicloud.com/folder/test.txt, the object name is folder/test.txt.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

ext

string

Extension of the file to be uploaded. It is automatically obtained from parameter mimeType or $(fname).

The name is compatible with mimeType.

override

string

Whether the uploaded object overwrites an existing one. The value is true or false.

If the name of the object to be uploaded already exists in the bucket, the existing object may be overwritten. true indicates that the existing object will be overwritten. false means the existing object will not be overwritten. When versioning is enabled for a bucket, override is always false.

imageInfo

string

Obtained basic information about the image to be uploaded. This parameter can be used only in the image uploading scenarios.

This variable contains the $(imageInfo.width) and $(imageInfo.height) fields, which indicate the width and height of an image.

NOTE:

If the size of an uploaded image exceeds 25 MB, the basic image information cannot be obtained using the magic variables related to imageInfo. As a result, the callback fails.

Responses

The responses follow the format of the original method's function call. For details, see Code Examples.

The following two methods are added to the response parameters:

1. ReadCallbackBody: This method allows you to read the response body returned by the callback server.

2. CloseCallbackBody: This method closes the response body returned by the callback server and must be called.

Code Examples

This example uses streaming to upload example/objectname to bucket examplebucket and specifies http://example.com:80 as the upload callback server.

 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Import the dependency package.
import (
     "fmt"
     "bytes"
     "encoding/base64"
     "encoding/json"
     "strings"
     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/intl/en-us/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 not advised to use hard coding, which may result in information leakage. 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. CN-Hong Kong is used here as an example. Replace it with the one currently in use.
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // 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)*/)

    input := &obs.PutObjectInput{}
    input.Bucket = "bucketname"
    input.Key = "objectname"
    input.Body = strings.NewReader("Hello OBS")
    callbackMap := map[string]string{}
    callbackMap["callbackUrl"] = "http://example.com:80"
    // callbackMap["callbackHost"] = "example.com"
    callbackMap["callbackBody"] = "filename=${object}&size=${size}&mimeType=${mimeType}"
    // callbackMap["callbackBodyType"] = "application/x-www-form-urlencoded"
    callbackBuffer := bytes.NewBuffer([]byte{})
    callbackEncoder := json.NewEncoder(callbackBuffer)
    callbackEncoder.SetEscapeHTML(false)
    err := callbackEncoder.Encode(callbackMap)
    if err != nil {
        fmt.Print(err)
        return
    }
    callbackVal := base64.StdEncoding.EncodeToString(callbackBuffer.Bytes())
    output, err := obsClient.PutObject(input, obs.WithCallbackHeader(callbackVal))
    if err == nil {
        // This method must be invoked.
        defer output.CloseCallbackBody()
        fmt.Printf("RequestId:%s\n", output.RequestId)
        fmt.Printf("ETag:%s\n", output.ETag)
        p := make([]byte, 1024)
        var readErr error
        var readCount int
        // Read the callback content.
        for {
            readCount, readErr = output.ReadCallbackBody(p)
            if readCount > 0 {
                fmt.Printf("%s", p[:readCount])
            }
            if readErr != nil {
                break
            }
        }
    } else if obsError, ok := err.(obs.ObsError); ok {
        fmt.Printf("Code:%s\n", obsError.Code)
        fmt.Printf("Message:%s\n", obsError.Message)
    }
}