url.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. // Package gurl provides useful API for URL handling.
  7. package gurl
  8. import (
  9. "net/url"
  10. "strings"
  11. )
  12. // Encode escapes the string so it can be safely placed
  13. // inside a URL query.
  14. func Encode(str string) string {
  15. return url.QueryEscape(str)
  16. }
  17. // Decode does the inverse transformation of Encode,
  18. // converting each 3-byte encoded substring of the form "%AB" into the
  19. // hex-decoded byte 0xAB.
  20. // It returns an error if any % is not followed by two hexadecimal
  21. // digits.
  22. func Decode(str string) (string, error) {
  23. return url.QueryUnescape(str)
  24. }
  25. // URL-encode according to RFC 3986.
  26. // See http://php.net/manual/en/function.rawurlencode.php.
  27. func RawEncode(str string) string {
  28. return strings.Replace(url.QueryEscape(str), "+", "%20", -1)
  29. }
  30. // Decode URL-encoded strings.
  31. // See http://php.net/manual/en/function.rawurldecode.php.
  32. func RawDecode(str string) (string, error) {
  33. return url.QueryUnescape(strings.Replace(str, "%20", "+", -1))
  34. }
  35. // Generate URL-encoded query string.
  36. // See http://php.net/manual/en/function.http-build-query.php.
  37. func BuildQuery(queryData url.Values) string {
  38. return queryData.Encode()
  39. }
  40. // Parse a URL and return its components.
  41. // -1: all; 1: scheme; 2: host; 4: port; 8: user; 16: pass; 32: path; 64: query; 128: fragment.
  42. // See http://php.net/manual/en/function.parse-url.php.
  43. func ParseURL(str string, component int) (map[string]string, error) {
  44. u, err := url.Parse(str)
  45. if err != nil {
  46. return nil, err
  47. }
  48. if component == -1 {
  49. component = 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128
  50. }
  51. var components = make(map[string]string)
  52. if (component & 1) == 1 {
  53. components["scheme"] = u.Scheme
  54. }
  55. if (component & 2) == 2 {
  56. components["host"] = u.Hostname()
  57. }
  58. if (component & 4) == 4 {
  59. components["port"] = u.Port()
  60. }
  61. if (component & 8) == 8 {
  62. components["user"] = u.User.Username()
  63. }
  64. if (component & 16) == 16 {
  65. components["pass"], _ = u.User.Password()
  66. }
  67. if (component & 32) == 32 {
  68. components["path"] = u.Path
  69. }
  70. if (component & 64) == 64 {
  71. components["query"] = u.RawQuery
  72. }
  73. if (component & 128) == 128 {
  74. components["fragment"] = u.Fragment
  75. }
  76. return components, nil
  77. }