upload.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package bfs
  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. "github.com/pkg/errors"
  13. )
  14. const (
  15. _uploadURL = "/bfs/%s/%s"
  16. _template = "%s\n%s\n%s\n%d\n"
  17. _method = "PUT"
  18. )
  19. // Upload upload picture or log file to bfs
  20. func (d *Dao) Upload(c context.Context, fileName, fileType string, expire int64, body io.Reader) (location string, err error) {
  21. var (
  22. url string
  23. req *http.Request
  24. resp *http.Response
  25. code int
  26. )
  27. client := &http.Client{}
  28. url = fmt.Sprintf(d.bfs+_uploadURL, d.bucket, fileName)
  29. if req, err = http.NewRequest(_method, url, body); err != nil {
  30. err = errors.Errorf("http.NewRequest(url(%s), body(%+v)) error(%+v)", url, body, err)
  31. return
  32. }
  33. authorization := authorize(d.key, d.secret, _method, d.bucket, fileName, expire)
  34. req.Header.Set("Host", d.bfs)
  35. req.Header.Add("Date", fmt.Sprint(expire))
  36. req.Header.Add("Authorization", authorization)
  37. req.Header.Add("Content-Type", fileType)
  38. resp, err = client.Do(req)
  39. if err != nil {
  40. err = errors.Errorf("resp.Do(%s) error(%+v)", url, err)
  41. return
  42. }
  43. defer resp.Body.Close()
  44. if resp.StatusCode != http.StatusOK {
  45. err = errors.Errorf("status code(%d) error(%+v)", resp.StatusCode, err)
  46. return
  47. }
  48. code, err = strconv.Atoi(resp.Header.Get("code"))
  49. if err != nil || code != http.StatusOK {
  50. err = errors.Errorf("response code(%d) error(%+v)", resp.StatusCode, err)
  51. return
  52. }
  53. location = resp.Header.Get("Location")
  54. return
  55. }
  56. // Authorize returns authorization for upload file to bfs
  57. func authorize(key, secret, method, bucket, file string, expire int64) (authorization string) {
  58. var (
  59. content string
  60. mac hash.Hash
  61. signature string
  62. )
  63. content = fmt.Sprintf(_template, method, bucket, file, expire)
  64. mac = hmac.New(sha1.New, []byte(secret))
  65. mac.Write([]byte(content))
  66. signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
  67. authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
  68. return
  69. }