dao.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package upload
  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. "go-common/app/admin/main/credit/conf"
  13. "go-common/library/log"
  14. httpx "go-common/library/net/http/blademaster"
  15. )
  16. const (
  17. _uploadURL = "/bfs/%s/%s"
  18. _template = "%s\n%s\n%s\n%d\n"
  19. _method = "PUT"
  20. _bucket = "test" //blocked
  21. )
  22. // Dao .
  23. type Dao struct {
  24. key string
  25. secret string
  26. host string
  27. client *httpx.Client
  28. }
  29. // New .
  30. func New(c *conf.Config) (d *Dao) {
  31. d = &Dao{
  32. key: c.BFS.Key,
  33. secret: c.BFS.Secret,
  34. host: c.Host.Bfs,
  35. client: httpx.NewClient(c.HTTPClient),
  36. }
  37. return
  38. }
  39. // Upload upload picture or log file to bfs
  40. func (d *Dao) Upload(c context.Context, fileName, fileType string, expire int64, body io.Reader) (location string, err error) {
  41. var (
  42. url string
  43. req *http.Request
  44. resp *http.Response
  45. code int
  46. )
  47. client := &http.Client{}
  48. url = fmt.Sprintf(d.host+_uploadURL, _bucket, fileName)
  49. if req, err = http.NewRequest(_method, url, body); err != nil {
  50. log.Error("http.NewRequest() Upload(%v) error(%v)", url, err)
  51. return
  52. }
  53. authorization := authorize(d.key, d.secret, _method, _bucket, fileName, expire)
  54. req.Header.Set("Host", d.host)
  55. req.Header.Add("Date", fmt.Sprint(expire))
  56. req.Header.Add("Authorization", authorization)
  57. req.Header.Add("Content-Type", fileType)
  58. resp, err = client.Do(req)
  59. if err != nil {
  60. log.Error("resp.Do(%s) error(%v)", url, err)
  61. return
  62. }
  63. defer resp.Body.Close()
  64. if resp.StatusCode != http.StatusOK {
  65. err = fmt.Errorf("status code error:%v", resp.StatusCode)
  66. return
  67. }
  68. code, err = strconv.Atoi(resp.Header.Get("code"))
  69. if err != nil || code != 200 {
  70. err = fmt.Errorf("response code error:%v", code)
  71. return
  72. }
  73. location = resp.Header.Get("Location")
  74. return
  75. }
  76. // authorize returns authorization for upload file to bfs
  77. func authorize(key, secret, method, bucket, file string, expire int64) (authorization string) {
  78. var (
  79. content string
  80. mac hash.Hash
  81. signature string
  82. )
  83. content = fmt.Sprintf(_template, method, bucket, file, expire)
  84. mac = hmac.New(sha1.New, []byte(secret))
  85. mac.Write([]byte(content))
  86. signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
  87. authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
  88. return
  89. }