bfs.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package dao
  2. import (
  3. "context"
  4. "crypto/hmac"
  5. "crypto/sha1"
  6. "encoding/base64"
  7. "errors"
  8. "fmt"
  9. "hash"
  10. "io"
  11. "net/http"
  12. "strconv"
  13. "go-common/library/log"
  14. )
  15. const (
  16. _uploadURL = "/%s/%s"
  17. _template = "%s\n%s\n%s\n%d\n"
  18. _method = "PUT"
  19. )
  20. var (
  21. errUpload = errors.New("Upload failed")
  22. )
  23. // Upload upload picture or log file to bfs
  24. func (d *Dao) Upload(c context.Context, fileName, fileType string, expire int64, body io.Reader) (location string, err error) {
  25. var (
  26. url string
  27. req *http.Request
  28. resp *http.Response
  29. header http.Header
  30. code string
  31. )
  32. bfsConf := d.c.Bfs
  33. url = fmt.Sprintf(bfsConf.Addr+_uploadURL, bfsConf.Bucket, fileName)
  34. if req, err = http.NewRequest(_method, url, body); err != nil {
  35. log.Error("http.NewRequest() Upload(%v) error(%v)", url, err)
  36. return
  37. }
  38. authorization := authorize(bfsConf.Key, bfsConf.Secret, _method, bfsConf.Bucket, fileName, expire)
  39. req.Header.Set("Host", bfsConf.Addr)
  40. req.Header.Add("Date", fmt.Sprint(expire))
  41. req.Header.Add("Authorization", authorization)
  42. req.Header.Add("Content-Type", fileType)
  43. resp, err = d.bfsClient.Do(req)
  44. if err != nil {
  45. log.Error("httpClient.Do(%s) error(%v)", url, err)
  46. return
  47. }
  48. if resp.StatusCode != http.StatusOK {
  49. log.Error("Upload url(%s) http.statuscode:%d", url, resp.StatusCode)
  50. err = errUpload
  51. return
  52. }
  53. header = resp.Header
  54. code = header.Get("Code")
  55. if code != strconv.Itoa(http.StatusOK) {
  56. log.Error("Upload url(%s) code:%s", url, code)
  57. err = errUpload
  58. return
  59. }
  60. location = header.Get("Location")
  61. return
  62. }
  63. // authorize returns authorization for upload file to bfs
  64. func authorize(key, secret, method, bucket, file string, expire int64) (authorization string) {
  65. var (
  66. content string
  67. mac hash.Hash
  68. signature string
  69. )
  70. content = fmt.Sprintf(_template, method, bucket, file, expire)
  71. mac = hmac.New(sha1.New, []byte(secret))
  72. mac.Write([]byte(content))
  73. signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
  74. authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
  75. return
  76. }