upload.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package dao
  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. )
  13. func authorize(key, secret, method, bucket string, expire int64) (authorization string) {
  14. var (
  15. content string
  16. hash2 hash.Hash
  17. signature string
  18. template = "%s\n%s\n\n%d\n"
  19. )
  20. content = fmt.Sprintf(template, method, bucket, expire)
  21. hash2 = hmac.New(sha1.New, []byte(secret))
  22. hash2.Write([]byte(content))
  23. signature = base64.StdEncoding.EncodeToString(hash2.Sum(nil))
  24. authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
  25. return
  26. }
  27. // UploadProxy upload file to bfs with no filename.
  28. func (d *Dao) UploadProxy(c context.Context, fileType string, expire int64, body []byte) (url string, err error) {
  29. var (
  30. req *http.Request
  31. resp *http.Response
  32. header http.Header
  33. code string
  34. bfs = d.c.Bfs
  35. uploadURL = "/%s"
  36. )
  37. url = fmt.Sprintf(bfs.Addr+uploadURL, bfs.Bucket)
  38. if req, err = http.NewRequest(http.MethodPut, url, bytes.NewReader(body)); err != nil {
  39. err = fmt.Errorf("dao.UploadProxy NewRequest error(%v)", err)
  40. return
  41. }
  42. authorization := authorize(bfs.Key, bfs.Secret, http.MethodPut, bfs.Bucket, expire)
  43. req.Header.Set("Host", bfs.Addr)
  44. req.Header.Add("Date", fmt.Sprint(expire))
  45. req.Header.Add("Authorization", authorization)
  46. req.Header.Add("Content-Type", fileType)
  47. if resp, err = http.DefaultClient.Do(req); err != nil {
  48. return
  49. }
  50. defer resp.Body.Close()
  51. if resp.StatusCode != http.StatusOK {
  52. err = fmt.Errorf("dao.UploadProxy error return_status(%d)", resp.StatusCode)
  53. return
  54. }
  55. header = resp.Header
  56. code = header.Get("Code")
  57. if code != strconv.Itoa(http.StatusOK) {
  58. err = fmt.Errorf("dao.UploadProxy Upload url(%s) return_code(%s)", url, code)
  59. return
  60. }
  61. url = header.Get("Location")
  62. return
  63. }