upbfs.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package dao
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/hmac"
  6. "crypto/sha1"
  7. "encoding/base64"
  8. "fmt"
  9. "hash"
  10. "net/http"
  11. "strconv"
  12. "time"
  13. "go-common/app/admin/main/creative/conf"
  14. "go-common/library/ecode"
  15. "go-common/library/log"
  16. )
  17. // bfs info
  18. const (
  19. _uploadURL = "/bfs/%s/%s"
  20. _template = "%s\n%s\n%s\n%d\n"
  21. _method = "PUT"
  22. _bucket = "creative"
  23. )
  24. // Upload upload picture or log file to bfs
  25. func (d *Dao) Upload(c context.Context, fileName string, fileType string, timing int64, data []byte, bfs *conf.Bfs) (location string, err error) {
  26. var (
  27. req *http.Request
  28. resp *http.Response
  29. code int
  30. client = &http.Client{Timeout: time.Duration(bfs.Timeout) * time.Millisecond}
  31. url = fmt.Sprintf(bfs.Host+_uploadURL, _bucket, fileName)
  32. )
  33. // prepare the data of the file and init the request
  34. buf := new(bytes.Buffer)
  35. _, err = buf.Write(data)
  36. if err != nil {
  37. log.Error("Upload.buf.Write.error(%v)", err)
  38. err = ecode.RequestErr
  39. return
  40. }
  41. if req, err = http.NewRequest(_method, url, buf); err != nil {
  42. log.Error("http.NewRequest() Upload(%v) error(%v)", url, err)
  43. return
  44. }
  45. // request setting
  46. authorization := authorize(bfs.Key, bfs.Secret, _method, _bucket, fileName, timing)
  47. req.Header.Set("Date", fmt.Sprint(timing))
  48. req.Header.Set("Authorization", authorization)
  49. req.Header.Set("Content-Type", fileType)
  50. resp, err = client.Do(req)
  51. // response treatment
  52. if err != nil {
  53. log.Error("Bfs client.Do(%s) error(%v)", url, err)
  54. return
  55. }
  56. defer resp.Body.Close()
  57. if resp.StatusCode != http.StatusOK {
  58. err = fmt.Errorf("Bfs status code error:%v", resp.StatusCode)
  59. return
  60. }
  61. code, err = strconv.Atoi(resp.Header.Get("code"))
  62. if err != nil || code != 200 {
  63. err = fmt.Errorf("Bfs response code error:%v", code)
  64. return
  65. }
  66. location = resp.Header.Get("Location")
  67. return
  68. }
  69. // authorize returns authorization for upload file to bfs
  70. func authorize(key, secret, method, bucket, file string, expire int64) (authorization string) {
  71. var (
  72. content string
  73. mac hash.Hash
  74. signature string
  75. )
  76. content = fmt.Sprintf(_template, method, bucket, file, expire)
  77. mac = hmac.New(sha1.New, []byte(secret))
  78. mac.Write([]byte(content))
  79. signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
  80. authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
  81. return
  82. }