bfs.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package dao
  2. import (
  3. "context"
  4. "crypto/hmac"
  5. "crypto/sha1"
  6. "encoding/base64"
  7. "fmt"
  8. "hash"
  9. "io"
  10. "net/http"
  11. "strconv"
  12. "time"
  13. "go-common/library/ecode"
  14. "go-common/library/log"
  15. )
  16. const _method = "PUT"
  17. // Upload upload bfs.
  18. func (d *Dao) Upload(c context.Context, fileType string, fileName string, body io.Reader) (location string, err error) {
  19. req, err := http.NewRequest(_method, d.c.Bfs.Addr+fileName, body)
  20. if err != nil {
  21. log.Error("http.NewRequest error (%v) | fileType(%s) body(%v)", err, fileType, body)
  22. return
  23. }
  24. expire := time.Now().Unix()
  25. authorization := authorize(d.c.Bfs.Key, d.c.Bfs.Secret, _method, d.c.Bfs.Bucket, fileName, expire)
  26. req.Header.Set("Host", d.c.Bfs.Addr)
  27. req.Header.Add("Date", fmt.Sprint(expire))
  28. req.Header.Add("Authorization", authorization)
  29. req.Header.Add("Content-Type", fileType)
  30. // timeout
  31. c, cancel := context.WithTimeout(c, time.Duration(d.c.Bfs.Timeout))
  32. req = req.WithContext(c)
  33. defer cancel()
  34. resp, err := d.client.Do(req)
  35. if err != nil {
  36. log.Error("d.Client.Do error(%v) | _url(%s) req(%v)", err, d.c.Bfs.Addr, req)
  37. err = ecode.BfsUploadServiceUnavailable
  38. return
  39. }
  40. if resp.StatusCode != http.StatusOK {
  41. log.Error("Upload http.StatusCode nq http.StatusOK (%d) | url(%s)", resp.StatusCode, d.c.Bfs.Addr)
  42. err = ecode.BfsUploadStatusErr
  43. return
  44. }
  45. header := resp.Header
  46. code := header.Get("Code")
  47. if code != strconv.Itoa(http.StatusOK) {
  48. log.Error("strconv.Itoa err, code(%s) | url(%s)", code, d.c.Bfs.Addr)
  49. err = ecode.BfsUploadCodeErr
  50. return
  51. }
  52. location = header.Get("Location")
  53. return
  54. }
  55. func authorize(key, secret, method, bucket string, fileName string, expire int64) (authorization string) {
  56. var (
  57. content string
  58. mac hash.Hash
  59. signature string
  60. )
  61. content = fmt.Sprintf("%s\n%s\n%s\n%d\n", method, bucket, fileName, expire)
  62. mac = hmac.New(sha1.New, []byte(secret))
  63. mac.Write([]byte(content))
  64. signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
  65. authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
  66. return
  67. }