upload.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package dao
  2. import (
  3. "context"
  4. "crypto/hmac"
  5. "crypto/sha1"
  6. "encoding/base64"
  7. "errors"
  8. "fmt"
  9. "hash"
  10. "io"
  11. "net/http"
  12. "strconv"
  13. "go-common/app/admin/main/up/conf"
  14. "go-common/library/log"
  15. )
  16. const (
  17. uploadurl = "/%s/%s"
  18. template = "%s\n%s\n%s\n%d\n"
  19. method = "PUT"
  20. )
  21. var (
  22. errUpload = errors.New("Upload failed")
  23. )
  24. // Upload upload picture or log file to bfs
  25. func Upload(c context.Context, fileName, fileType string, expire int64, body io.Reader, bfsConf *conf.Bfs) (location string, err error) {
  26. var (
  27. url string
  28. req *http.Request
  29. resp *http.Response
  30. header http.Header
  31. code string
  32. )
  33. url = fmt.Sprintf(bfsConf.Addr+uploadurl, bfsConf.Bucket, fileName)
  34. if req, err = http.NewRequest(method, url, body); err != nil {
  35. log.Error("http.NewRequest() Upload(%v) error(%v)", url, err)
  36. return
  37. }
  38. log.Info("upload url={%s}", url)
  39. authorization := Authorize(bfsConf.Key, bfsConf.Secret, method, bfsConf.Bucket, fileName, expire)
  40. req.Header.Set("Host", bfsConf.Addr)
  41. req.Header.Add("Date", fmt.Sprint(expire))
  42. req.Header.Add("Authorization", authorization)
  43. req.Header.Add("Content-Type", fileType)
  44. resp, err = http.DefaultClient.Do(req)
  45. if err != nil {
  46. log.Error("httpClient.Do(%s) error(%v)", url, err)
  47. return
  48. }
  49. if resp.StatusCode != http.StatusOK {
  50. log.Error("Upload url(%s) http.statuscode:%d", url, resp.StatusCode)
  51. err = errUpload
  52. return
  53. }
  54. header = resp.Header
  55. code = header.Get("Code")
  56. if code != strconv.Itoa(http.StatusOK) {
  57. log.Error("Upload url(%s) code:%s", url, code)
  58. err = errUpload
  59. return
  60. }
  61. location = header.Get("Location")
  62. return
  63. }
  64. // Authorize authorize returns authorization for upload file to bfs
  65. func Authorize(key, secret, method, bucket, file string, expire int64) (authorization string) {
  66. var (
  67. content string
  68. mac hash.Hash
  69. signature string
  70. )
  71. content = fmt.Sprintf(template, method, bucket, file, expire)
  72. mac = hmac.New(sha1.New, []byte(secret))
  73. mac.Write([]byte(content))
  74. signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
  75. authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
  76. return
  77. }