由于阿里那边没有提供golang示例只有自己写一个,如果发现问题希望给予纠正。
配置信息自己替换。
调用方法
Putobject("4.txt", []byte("123123fasdfasdfadfadfasfasdfsadf"))
package oss import ( "bytes" "crypto/hmac" "crypto/sha1" "encoding/base64" "fmt" "io/ioutil" "mime" "net/http" "path/filepath" "time" ) func authorization(accesskeysecret, method, filemd5, filetype, date, CanonicalizedOSSHeaders, CanonicalizedResource string) string { h := hmac.New(sha1.New, []byte(accesskeysecret)) s := fmt.Sprintf("%v\n%v\n%v\n%v\n%v%v", method, filemd5, filetype, date, CanonicalizedOSSHeaders, CanonicalizedResource) h.Write([]byte(s)) return base64.StdEncoding.EncodeToString(h.Sum(nil)) } var client = &http.Client{Timeout: 20 * time.Second} func Putobject(key string, b []byte) bool { url := fmt.Sprintf("http://%v.%v/%v", config.Cfg.Oss.Bucket, config.Cfg.Oss.Server, key) req, err := http.NewRequest("PUT", url, bytes.NewReader(b)) if err != nil { logger.Debug("Putobject.NewRequest", err) return false } else { defer req.Body.Close() } dt := time.Now().UTC().Format("Mon, 02 Jan 2006 15:04:05 GMT") ct := mime.TypeByExtension(filepath.Ext(key)) req.Header.Add("Content-Length", string(len(b))) req.Header.Add("Content-Type", ct) req.Header.Add("Date", dt) req.Header.Add("Authorization", "OSS "+config.Cfg.Oss.Keyid+":"+authorization(config.Cfg.Oss.Keysecret, "PUT", "", ct, dt, "", "/"+config.Cfg.Oss.Bucket+"/"+key)) if resp, err := client.Do(req); err == nil { if resp_body, err := ioutil.ReadAll(resp.Body); err == nil { if resp.StatusCode == 200 { // for k, v := range resp.Header { // fmt.Printf("%s ==== %s\n", k, v) // } return true } else { logger.Debug("OSS错误返回|", url, ":", string(resp.StatusCode), ":", string(resp_body)) return false } } else { logger.Debug("Putobject.ioutil.ReadAll", err) return false } } else { logger.Debug("Putobject.client.Do", err) return false } }
有疑问加站长微信联系(非本文作者)