upbfs.go 2.3 KB

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