upload.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package http
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/hmac"
  6. "crypto/sha1"
  7. "encoding/base64"
  8. "fmt"
  9. "hash"
  10. "net/http"
  11. "strconv"
  12. "time"
  13. "go-common/library/ecode"
  14. "go-common/library/log"
  15. )
  16. // bfs info
  17. const (
  18. _uploadURL = "/bfs/%s/%s"
  19. _template = "%s\n%s\n%s\n%d\n"
  20. _method = "PUT"
  21. _bucket = "creative"
  22. )
  23. // Upload upload picture or log file to bfs
  24. func (d *Dao) Upload(c context.Context, fileName string, fileType string, timing int64, data []byte) (location string, err error) {
  25. var (
  26. req *http.Request
  27. resp *http.Response
  28. code int
  29. client = &http.Client{Timeout: time.Duration(d.c.Bfs.Timeout) * time.Millisecond}
  30. url = fmt.Sprintf(d.c.Bfs.Host+_uploadURL, _bucket, fileName)
  31. )
  32. // prepare the data of the file and init the request
  33. buf := new(bytes.Buffer)
  34. _, err = buf.Write(data)
  35. if err != nil {
  36. log.Error("Upload.buf.Write.error(%v)", err)
  37. err = ecode.RequestErr
  38. return
  39. }
  40. if req, err = http.NewRequest(_method, url, buf); err != nil {
  41. log.Error("http.NewRequest() Upload(%v) error(%v)", url, err)
  42. return
  43. }
  44. // request setting
  45. authorization := authorize(d.c.Bfs.Key, d.c.Bfs.Secret, _method, _bucket, fileName, timing)
  46. req.Header.Set("Date", fmt.Sprint(timing))
  47. req.Header.Set("Authorization", authorization)
  48. req.Header.Set("Content-Type", fileType)
  49. resp, err = client.Do(req)
  50. // response treatment
  51. if err != nil {
  52. log.Error("Bfs client.Do(%s) error(%v)", url, err)
  53. return
  54. }
  55. defer resp.Body.Close()
  56. if resp.StatusCode != http.StatusOK {
  57. err = fmt.Errorf("Bfs status code error:%v", resp.StatusCode)
  58. return
  59. }
  60. code, err = strconv.Atoi(resp.Header.Get("code"))
  61. if err != nil || code != 200 {
  62. err = fmt.Errorf("Bfs response code error:%v", code)
  63. return
  64. }
  65. location = resp.Header.Get("Location")
  66. return
  67. }
  68. // authorize returns authorization for upload file to bfs
  69. func authorize(key, secret, method, bucket, file string, expire int64) (authorization string) {
  70. var (
  71. content string
  72. mac hash.Hash
  73. signature string
  74. )
  75. content = fmt.Sprintf(_template, method, bucket, file, expire)
  76. mac = hmac.New(sha1.New, []byte(secret))
  77. mac.Write([]byte(content))
  78. signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
  79. authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
  80. return
  81. }