This topic describes how to use Object Storage Service (OSS) SDK for Go to upload an object by including signatures in the Authorization header.
Examples
The following sample code provides an example on how to use OSS SDK for Go 1.7.6 to upload an object by including signatures in the Authorization header:
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
)
func main() {
// Specify the name of the bucket. Example: examplebucket.
bucketname := "examplebucket"
// Specify the public endpoint of the bucket.
endpoint := "oss-cn-hangzhou.aliyuncs.com"
// Specify the full path of the object. Do not include the bucket name in the full path. Example: example/test.txt.
objectname := "examplefile.txt"
// Obtain access credentials from environment variables. Before you run the code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accesskey := os.Getenv("OSS_ACCESS_KEY_ID")
accesskeysecret := os.Getenv("OSS_ACCESS_KEY_SECRET")
contenttype := "application/json"
gmtdate := time.Now().UTC().Format(http.TimeFormat)
stringtosgin := "PUT\n\n" + contenttype + "\n" + gmtdate + "\n" + "/" + bucketname + "/" + objectname
key := []byte(accesskeysecret)
mac := hmac.New(sha1.New, key)
mac.Write([]byte(stringtosgin))
// Perform Base64 encoding.
signature := base64.StdEncoding.EncodeToString(mac.Sum(nil))
url := "http://" + bucketname + "." + endpoint + "/" + objectname
payload := strings.NewReader("{go:test}")
req, _ := http.NewRequest("PUT", url, payload)
req.Header.Add("Content-Type", contenttype)
req.Header.Add("Authorization", "OSS "+accesskey+":"+signature)
req.Header.Add("Date", gmtdate)
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(res)
fmt.Println(string(body))
}Sample output:
&{200 OK 200 HTTP/1.1 1 1 map[Connection:[keep-alive] Content-Length:[0] Content-Md5:[BBFHkvGJ4s7YGacim2mbCg==] Date:[Thu, 14 Sep 2023 09:28:19 GMT] Etag:["04114792F189E2CED819A7229B69****"] Server:[AliyunOSS] X-Oss-Hash-Crc64ecma:[1342951013225723****] X-Oss-Request-Id:[6502D233818A31353126****] X-Oss-Server-Time:[126]] {} 0 [] false false map[] 0xc000134000 <nil>}