NatsQiniu.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package NatsServer
  2. import (
  3. "context"
  4. "github.com/qiniu/go-sdk/v7/auth/qbox"
  5. "github.com/qiniu/go-sdk/v7/storage"
  6. "github.com/vmihailenco/msgpack/v5"
  7. "strings"
  8. "time"
  9. )
  10. func (m *NatsImpl) Qiniu_UploadToken(T_suffix string, T_MimeLimit string) (string, bool) {
  11. type Qiniu_UploadToken struct {
  12. T_suffix string
  13. T_MimeLimit string
  14. }
  15. b, err := msgpack.Marshal(&Qiniu_UploadToken{
  16. T_suffix: T_suffix,
  17. T_MimeLimit: T_MimeLimit,
  18. })
  19. if err != nil {
  20. panic(err)
  21. }
  22. // 请求-响应, 向 test3 发布一个 `help me` 请求数据,设置超时间3秒,如果有多个响应,只接收第一个收到的消息
  23. msg, err := m.nats.Request("Qiniu_UploadToken", b, 3*time.Second)
  24. if err != nil {
  25. return string(msg.Data), false
  26. }
  27. return string(msg.Data), true
  28. }
  29. func (m *NatsImpl) Qiniu_UploadFile(localFile string, name string) (string, bool) {
  30. // 获取 七牛云的 配置信息
  31. msg, err := m.nats.Request("Qiniu_Token", []byte(""), 3*time.Second)
  32. if err != nil {
  33. return string(msg.Data), false
  34. }
  35. Qiniu_cs := strings.Split(string(msg.Data), "|")
  36. Qiniu_AccessKey := Qiniu_cs[0]
  37. Qiniu_SecretKey := Qiniu_cs[1]
  38. Qiniu_BUCKET := Qiniu_cs[2]
  39. Qiniu_Url := Qiniu_cs[3]
  40. // 开始上传 七牛云
  41. Qiniu := qbox.NewMac(Qiniu_AccessKey, Qiniu_SecretKey)
  42. // 自定义返回值结构体
  43. type MyPutRet struct {
  44. Key string
  45. Hash string
  46. Fsize int
  47. Bucket string
  48. Name string
  49. }
  50. putPolicy := storage.PutPolicy{
  51. Scope: Qiniu_BUCKET,
  52. ReturnBody: `{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}`,
  53. }
  54. upToken := putPolicy.UploadToken(Qiniu)
  55. cfg := storage.Config{}
  56. formUploader := storage.NewFormUploader(&cfg)
  57. ret := MyPutRet{}
  58. putExtra := storage.PutExtra{
  59. Params: map[string]string{
  60. "x:name": "github logo",
  61. },
  62. }
  63. err = formUploader.PutFile(context.Background(), &ret, upToken, name, localFile, &putExtra)
  64. if err != nil {
  65. return "", false
  66. }
  67. return Qiniu_Url + name, true
  68. }