upbfs.go 2.1 KB

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