upload.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. "go-common/library/net/trace"
  15. )
  16. const (
  17. _uploadURL = "/%s/%s"
  18. _moduleName = "http_client"
  19. _template = "%s\n%s\n%s\n%d\n"
  20. _method = "PUT"
  21. )
  22. var (
  23. errUpload = errors.New("Upload failed")
  24. )
  25. // Upload upload picture or log file to bfs
  26. func (d *Dao) Upload(c context.Context, fileName, fileType string, expire int64, body io.Reader) (location string, err error) {
  27. var (
  28. url string
  29. req *http.Request
  30. resp *http.Response
  31. header http.Header
  32. code string
  33. )
  34. bfsConf := d.c.Bfs
  35. url = fmt.Sprintf(bfsConf.Addr+_uploadURL, bfsConf.Bucket, fileName)
  36. if req, err = http.NewRequest(_method, url, body); err != nil {
  37. log.Error("http.NewRequest() Upload(%v) error(%v)", url, err)
  38. return
  39. }
  40. authorization := authorize(bfsConf.Key, bfsConf.Secret, _method, bfsConf.Bucket, fileName, expire)
  41. req.Header.Set("Host", bfsConf.Addr)
  42. req.Header.Add("Date", fmt.Sprint(expire))
  43. req.Header.Add("Authorization", authorization)
  44. req.Header.Add("Content-Type", fileType)
  45. t, ok := trace.FromContext(c)
  46. if ok {
  47. t = t.Fork("http_client", "bfs_upload")
  48. t.SetTag(trace.String(trace.TagAddress, _moduleName), trace.String(trace.TagComment, req.URL.Path))
  49. }
  50. resp, err = http.DefaultClient.Do(req)
  51. if err != nil {
  52. t.Finish(&err)
  53. log.Error("httpClient.Do(%s) error(%v)", url, err)
  54. return
  55. }
  56. if resp.StatusCode != http.StatusOK {
  57. log.Error("Upload url(%s) http.statuscode:%d", url, resp.StatusCode)
  58. err = errUpload
  59. return
  60. }
  61. header = resp.Header
  62. code = header.Get("Code")
  63. if code != strconv.Itoa(http.StatusOK) {
  64. log.Error("Upload url(%s) code:%s", url, code)
  65. err = errUpload
  66. return
  67. }
  68. location = header.Get("Location")
  69. return
  70. }
  71. // authorize returns authorization for upload file to bfs
  72. func authorize(key, secret, method, bucket, file string, expire int64) (authorization string) {
  73. var (
  74. content string
  75. mac hash.Hash
  76. signature string
  77. )
  78. content = fmt.Sprintf(_template, method, bucket, file, expire)
  79. mac = hmac.New(sha1.New, []byte(secret))
  80. mac.Write([]byte(content))
  81. signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
  82. authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
  83. return
  84. }