Last active
March 8, 2018 02:26
-
-
Save e7/ecfab58dea1c6394599b3f8ea81e3678 to your computer and use it in GitHub Desktop.
七牛云上传示例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package token | |
import ( | |
"io/ioutil" | |
"encoding/json" | |
"net/http" | |
"github.com/sirupsen/logrus" | |
"github.com/qiniu/api.v7/storage" | |
"fmt" | |
"github.com/qiniu/api.v7/auth/qbox" | |
"strings" | |
) | |
const ( | |
TOKEN_TYPE_AVATAR = "avatar" | |
) | |
type params struct { | |
TokenType string `json:"token_type"` // 获取的token类型 | |
KeySuffix string `json:"key_suffix"` // key后缀 | |
} | |
func (this *params) NotAllValued() bool { | |
return (this.TokenType == "") || (this.KeySuffix == "") | |
} | |
// 获取上传凭证 | |
func GetUploadToken(rspw http.ResponseWriter, req *http.Request) { | |
var err error | |
var data []byte | |
rspw.Header().Set("Access-Control-Allow-Origin", "*") // 测试允许跨域访问 | |
rspw.Header().Set("Content-Type", "application/json") | |
if data, err = ioutil.ReadAll(req.Body); nil != err { | |
logrus.Printf("invalid request:%s\n", err.Error()) | |
rspw.WriteHeader(http.StatusBadRequest) | |
return | |
} | |
prm := ¶ms{} | |
if err = json.Unmarshal(data, prm); nil != err { | |
logrus.Printf("invalid json:%s\n", err.Error()) | |
rspw.WriteHeader(http.StatusBadRequest) | |
return | |
} | |
if prm.NotAllValued() { | |
rspw.Write([]byte( | |
`{"error_no":"401","error_msg":"missing arguments"}`, | |
)) | |
return | |
} | |
conf := GetConfigInstance() | |
switch prm.TokenType { | |
case TOKEN_TYPE_AVATAR: | |
fullKey := strings.Join([]string{"images:avatar", prm.KeySuffix}, "/") | |
uploadToken := (&storage.PutPolicy{ | |
Scope: fullKey, | |
Expires: 86400, | |
IsPrefixalScope: 0, | |
InsertOnly: 0, | |
CallbackURL: strings.Join([]string{conf.CallbackURL, "avatar"}, "/"), | |
CallbackBodyType: "application/json", | |
CallbackBody: `{ | |
"api":"avatar", "uid":"$(x:uid)", | |
"bucket":"$(bucket)","key":"$(key)","hash":"$(etag)" | |
}`, | |
}).UploadToken(qbox.NewMac(conf.AccessKey, conf.SecretKey)) | |
if "" == strings.TrimSpace(uploadToken) { | |
logrus.Printf("upload token to qiniu failed\n") | |
break | |
} | |
rspw.Write([]byte(fmt.Sprintf( | |
`{"error_no":"200","error_msg":"success","upload_token":"%s","full_key":"%s"}`, | |
uploadToken, strings.Split(fullKey,":")[1], | |
))) | |
default: | |
rspw.Write([]byte( | |
`{"error_no":"401","error_msg":"invalid token_type"}`, | |
)) | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
上传回调的业务端需要清除cnd缓存
cdnMng := cdn.NewCdnManager(qbox.NewMac("xxx","xxx"))
ret, err := cdnMng.RefreshUrls([]string{"http://xxxx/xxxx","http://xxxxx/xxxxx"})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(ret.Code)
fmt.Println(ret.RequestID)