12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- package qiniu
- import (
- "context"
- "github.com/qiniu/go-sdk/v7/auth/qbox"
- "github.com/qiniu/go-sdk/v7/storage"
- "net/http"
- "time"
- )
- var _ QiNiu = (*qiNiu)(nil)
- type QiNiu interface {
- i()
- GetUploadToken(ttl uint64) string
- GetPrivateURL(key string, ttl uint64) string
- VerifyCallback(req *http.Request) (bool, error)
- UploadFile(key, localFile string, zone *storage.Region) (*storage.PutRet, error)
- DelFile(key string, zone *storage.Region) error
- }
- type qiNiu struct {
- mac *qbox.Mac
- bucket string
- domain string
- callbackURL string
- }
- type PutRet struct {
- Key string `json:"key"`
- Hash string `json:"hash"`
- Fsize int `json:"fsize"`
- }
- func New(key, secret, bucket, domain, callbackURL string) QiNiu {
- return &qiNiu{
- mac: qbox.NewMac(key, secret),
- bucket: bucket,
- domain: domain,
- callbackURL: callbackURL,
- }
- }
- func (q *qiNiu) i() {}
- func (q *qiNiu) GetUploadToken(ttl uint64) string {
- putPolicy := storage.PutPolicy{
- Scope: q.bucket,
- Expires: ttl,
- }
- return putPolicy.UploadToken(q.mac)
- }
- func (q *qiNiu) GetPrivateURL(key string, ttl uint64) string {
- deadline := time.Now().Add(time.Second * time.Duration(ttl)).Unix()
- return storage.MakePrivateURL(q.mac, q.domain, key, deadline)
- }
- func (q *qiNiu) VerifyCallback(req *http.Request) (bool, error) {
- return q.mac.VerifyCallback(req)
- }
- func (q *qiNiu) UploadFile(key, localFile string, zone *storage.Region) (*storage.PutRet, error) {
- upToken := q.GetUploadToken(60)
- cfg := storage.Config{
- Zone: zone, //空间对应的机房
- UseHTTPS: true, //是否使用https域名
- UseCdnDomains: true, //上传是否使用CDN上传加速
- }
- //构建表单上传的对象
- formUploader := storage.NewFormUploader(&cfg)
- ret := &storage.PutRet{}
- // 可选配置
- putExtra := storage.PutExtra{}
- err := formUploader.PutFile(context.Background(), ret, upToken, key, localFile, &putExtra)
- if err != nil {
- return nil, err
- }
- return ret, nil
- }
- func (q *qiNiu) DelFile(key string, zone *storage.Region) error {
- cfg := storage.Config{
- Zone: zone, //空间对应的机房
- UseHTTPS: true, //是否使用https域名
- UseCdnDomains: true, //上传是否使用CDN上传加速
- }
- bucketManager := storage.NewBucketManager(q.mac, &cfg)
- err := bucketManager.Delete(q.bucket, key)
- if err != nil {
- return err
- }
- return nil
- }
|