You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.0 KiB

  1. package cos
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "crypto/sha1"
  6. "fmt"
  7. "net/http"
  8. "net/url"
  9. )
  10. // 计算 md5 或 sha1 时的分块大小
  11. const calDigestBlockSize = 1024 * 1024 * 10
  12. func calMD5Digest(msg []byte) []byte {
  13. // TODO: 分块计算,减少内存消耗
  14. m := md5.New()
  15. m.Write(msg)
  16. return m.Sum(nil)
  17. }
  18. func calSHA1Digest(msg []byte) []byte {
  19. // TODO: 分块计算,减少内存消耗
  20. m := sha1.New()
  21. m.Write(msg)
  22. return m.Sum(nil)
  23. }
  24. // cloneRequest returns a clone of the provided *http.Request. The clone is a
  25. // shallow copy of the struct and its Header map.
  26. func cloneRequest(r *http.Request) *http.Request {
  27. // shallow copy of the struct
  28. r2 := new(http.Request)
  29. *r2 = *r
  30. // deep copy of the Header
  31. r2.Header = make(http.Header, len(r.Header))
  32. for k, s := range r.Header {
  33. r2.Header[k] = append([]string(nil), s...)
  34. }
  35. return r2
  36. }
  37. // encodeURIComponent like same function in javascript
  38. //
  39. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
  40. //
  41. // http://www.ecma-international.org/ecma-262/6.0/#sec-uri-syntax-and-semantics
  42. func encodeURIComponent(s string) string {
  43. var b bytes.Buffer
  44. written := 0
  45. for i, n := 0, len(s); i < n; i++ {
  46. c := s[i]
  47. switch c {
  48. case '-', '_', '.', '!', '~', '*', '\'', '(', ')':
  49. continue
  50. default:
  51. // Unreserved according to RFC 3986 sec 2.3
  52. if 'a' <= c && c <= 'z' {
  53. continue
  54. }
  55. if 'A' <= c && c <= 'Z' {
  56. continue
  57. }
  58. if '0' <= c && c <= '9' {
  59. continue
  60. }
  61. }
  62. b.WriteString(s[written:i])
  63. fmt.Fprintf(&b, "%%%02X", c)
  64. written = i + 1
  65. }
  66. if written == 0 {
  67. return s
  68. }
  69. b.WriteString(s[written:])
  70. return b.String()
  71. }
  72. func decodeURIComponent(s string) (string, error) {
  73. decodeStr, err := url.QueryUnescape(s)
  74. if err != nil {
  75. return s, err
  76. }
  77. return decodeStr, err
  78. }
  79. func DecodeURIComponent(s string) (string, error) {
  80. return DecodeURIComponent(s)
  81. }
  82. func EncodeURIComponent(s string) string {
  83. return encodeURIComponent(s)
  84. }