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.

114 lines
2.2 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, excluded ...[]byte) 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. if len(excluded) > 0 {
  62. conti := false
  63. for _, ch := range excluded[0] {
  64. if ch == c {
  65. conti = true
  66. break
  67. }
  68. }
  69. if conti {
  70. continue
  71. }
  72. }
  73. }
  74. b.WriteString(s[written:i])
  75. fmt.Fprintf(&b, "%%%02X", c)
  76. written = i + 1
  77. }
  78. if written == 0 {
  79. return s
  80. }
  81. b.WriteString(s[written:])
  82. return b.String()
  83. }
  84. func decodeURIComponent(s string) (string, error) {
  85. decodeStr, err := url.QueryUnescape(s)
  86. if err != nil {
  87. return s, err
  88. }
  89. return decodeStr, err
  90. }
  91. func DecodeURIComponent(s string) (string, error) {
  92. return DecodeURIComponent(s)
  93. }
  94. func EncodeURIComponent(s string) string {
  95. return encodeURIComponent(s)
  96. }