storage.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package qiniu
  2. import (
  3. "context"
  4. "github.com/qiniu/go-sdk/v7/auth/qbox"
  5. "github.com/qiniu/go-sdk/v7/storage"
  6. "net/http"
  7. "time"
  8. )
  9. var _ QiNiu = (*qiNiu)(nil)
  10. type QiNiu interface {
  11. i()
  12. GetUploadToken(ttl uint64) string
  13. GetPrivateURL(key string, ttl uint64) string
  14. VerifyCallback(req *http.Request) (bool, error)
  15. UploadFile(key, localFile string, zone *storage.Region) (*storage.PutRet, error)
  16. DelFile(key string, zone *storage.Region) error
  17. }
  18. type qiNiu struct {
  19. mac *qbox.Mac
  20. bucket string
  21. domain string
  22. callbackURL string
  23. }
  24. type PutRet struct {
  25. Key string `json:"key"`
  26. Hash string `json:"hash"`
  27. Fsize int `json:"fsize"`
  28. }
  29. func New(key, secret, bucket, domain, callbackURL string) QiNiu {
  30. return &qiNiu{
  31. mac: qbox.NewMac(key, secret),
  32. bucket: bucket,
  33. domain: domain,
  34. callbackURL: callbackURL,
  35. }
  36. }
  37. func (q *qiNiu) i() {}
  38. func (q *qiNiu) GetUploadToken(ttl uint64) string {
  39. putPolicy := storage.PutPolicy{
  40. Scope: q.bucket,
  41. Expires: ttl,
  42. }
  43. return putPolicy.UploadToken(q.mac)
  44. }
  45. func (q *qiNiu) GetPrivateURL(key string, ttl uint64) string {
  46. deadline := time.Now().Add(time.Second * time.Duration(ttl)).Unix()
  47. return storage.MakePrivateURL(q.mac, q.domain, key, deadline)
  48. }
  49. func (q *qiNiu) VerifyCallback(req *http.Request) (bool, error) {
  50. return q.mac.VerifyCallback(req)
  51. }
  52. func (q *qiNiu) UploadFile(key, localFile string, zone *storage.Region) (*storage.PutRet, error) {
  53. upToken := q.GetUploadToken(60)
  54. cfg := storage.Config{
  55. Zone: zone, //空间对应的机房
  56. UseHTTPS: true, //是否使用https域名
  57. UseCdnDomains: true, //上传是否使用CDN上传加速
  58. }
  59. //构建表单上传的对象
  60. formUploader := storage.NewFormUploader(&cfg)
  61. ret := &storage.PutRet{}
  62. // 可选配置
  63. putExtra := storage.PutExtra{}
  64. err := formUploader.PutFile(context.Background(), ret, upToken, key, localFile, &putExtra)
  65. if err != nil {
  66. return nil, err
  67. }
  68. return ret, nil
  69. }
  70. func (q *qiNiu) DelFile(key string, zone *storage.Region) error {
  71. cfg := storage.Config{
  72. Zone: zone, //空间对应的机房
  73. UseHTTPS: true, //是否使用https域名
  74. UseCdnDomains: true, //上传是否使用CDN上传加速
  75. }
  76. bucketManager := storage.NewBucketManager(q.mac, &cfg)
  77. err := bucketManager.Delete(q.bucket, key)
  78. if err != nil {
  79. return err
  80. }
  81. return nil
  82. }