OSS签名Header实现Demo(GoLang)

  1. 云栖社区>
  2. 博客>
  3. 正文

OSS签名Header实现Demo(GoLang)

gabel 2020-04-10 21:30:40 浏览544

概述

OSS的集成上传和下载提供了SDK可以直接使用,但实际使用中一些用户受限环境或者设备限制需要使用api方式来实现上传和下载,本文以PutObject接口为例,提供了GoLang实现的demo。
注:建议优先使用OSS提供SDK,本文提供的只是签名实现上传demo,实际使用中需要结合业务来进行改动代码

详细信息

PutObject实现demo(测试环境go1.7.6):

package main

import (
 "crypto/hmac"
 "crypto/sha1"
 "encoding/base64"
 "fmt"
 "io/ioutil"
 "net/http"
 "strings"
 "time"
)

func main() {
 bucketname := "bucket名称"
 endpoint := "oss-cn-hangzhou.aliyuncs.com"
 objectname := "mytest/go.txt"  //存储路径
 accesskey := "xx"  //您的Accesskey
 accesskeysecret := "xx" //您的Accesskeysecret
 contenttype := "application/json"
 gmtdate := time.Now().UTC().Format(http.TimeFormat)
 stringtosgin := "PUT\n\n" + contenttype + "\n" + gmtdate + "\n" + "/" + bucketname + "/" + objectname
 // HMACSHA1 实现部分
 key := []byte(accesskeysecret)
 mac := hmac.New(sha1.New, key)
 mac.Write([]byte(stringtosgin))
 //进行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))
}

 

输出结果

{200 OK 200 HTTP/1.1 1 1 map[Server:[AliyunOSS] Date:[Thu, 09 Apr 2020 09:16:47 GMT] Content-Length:[0] Connection:[keep-alive] X-Oss-Request-Id:[5E8EE7FF990C633330489D8D] Etag:["04114792F189E2CED819A7229B699B0A"] X-Oss-Hash-Crc64ecma:[13429510132257231065] Content-Md5:[BBFHkvGJ4s7YGacim2mbCg==] X-Oss-Server-Time:[92]] 0x71d940 0 [] false false map[] 0xc0420c20f0 <nil>}