escape.go 885 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // based on https://github.com/golang/go/blob/master/src/net/url/url.go
  2. // Copyright 2009 The Go Authors. All rights reserved.
  3. // Use of this source code is governed by a BSD-style
  4. // license that can be found in the LICENSE file.
  5. package core
  6. func shouldEscape(c byte) bool {
  7. if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' || c == '_' || c == '-' || c == '~' || c == '.' {
  8. return false
  9. }
  10. return true
  11. }
  12. func escape(s string) string {
  13. hexCount := 0
  14. for i := 0; i < len(s); i++ {
  15. c := s[i]
  16. if shouldEscape(c) {
  17. hexCount++
  18. }
  19. }
  20. if hexCount == 0 {
  21. return s
  22. }
  23. t := make([]byte, len(s)+2*hexCount)
  24. j := 0
  25. for i := 0; i < len(s); i++ {
  26. switch c := s[i]; {
  27. case shouldEscape(c):
  28. t[j] = '%'
  29. t[j+1] = "0123456789ABCDEF"[c>>4]
  30. t[j+2] = "0123456789ABCDEF"[c&15]
  31. j += 3
  32. default:
  33. t[j] = s[i]
  34. j++
  35. }
  36. }
  37. return string(t)
  38. }