bfs.go 2.3 KB

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