Topik ini menjelaskan cara menggunakan Object Storage Service (OSS) SDK untuk Go dalam mengunggah objek dengan menyertakan tanda tangan di header Authorization.
Contoh
Kode sampel berikut menunjukkan cara menggunakan OSS SDK untuk Go versi 1.7.6 untuk mengunggah objek dengan menyertakan tanda tangan di header Authorization:
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
)
func main() {
// Tentukan nama bucket. Contoh: examplebucket.
bucketname := "examplebucket"
// Tentukan endpoint publik dari bucket.
endpoint := "oss-cn-hangzhou.aliyuncs.com"
// Tentukan jalur lengkap objek. Jangan sertakan nama bucket dalam jalur lengkap. Contoh: example/test.txt.
objectname := "examplefile.txt"
// Dapatkan kredensial akses dari variabel lingkungan. Sebelum menjalankan kode, pastikan variabel lingkungan OSS_ACCESS_KEY_ID dan OSS_ACCESS_KEY_SECRET telah dikonfigurasi.
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))
// Lakukan pengkodean Base64.
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))
}Contoh keluaran:
&{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>}