main.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package yu_url
  2. import "strings"
  3. // Values maps a string key to a list of values.
  4. // It is typically used for query parameters and form values.
  5. // Unlike in the http.Header map, the keys in a Values map
  6. // are case-sensitive.
  7. type Values map[string][]string
  8. // Get gets the first value associated with the given key.
  9. // If there are no values associated with the key, Get returns
  10. // the empty string. To access multiple values, use the map
  11. // directly.
  12. func (v Values) Get(key string) string {
  13. vs := v[key]
  14. if len(vs) == 0 {
  15. return ""
  16. }
  17. return vs[0]
  18. }
  19. // Gets gets the first value associated with the given key.
  20. // If there are no values associated with the key, Get returns
  21. // the empty string. To access multiple values, use the map
  22. // directly.
  23. func (v Values) Gets(key string) []string {
  24. return v[key]
  25. }
  26. // Set sets the key to value. It replaces any existing
  27. // values.
  28. func (v Values) Set(key, value string) {
  29. v[key] = []string{value}
  30. }
  31. // Add adds the value to key. It appends to any existing
  32. // values associated with key.
  33. func (v Values) Add(key, value string) {
  34. v[key] = append(v[key], value)
  35. }
  36. // Del deletes the values associated with key.
  37. func (v Values) Del(key string) {
  38. delete(v, key)
  39. }
  40. // Has checks whether a given key is set.
  41. func (v Values) Has(key string) bool {
  42. _, ok := v[key]
  43. return ok
  44. }
  45. // ParseQuery parses the URL-encoded query string and returns
  46. // a map listing the values specified for each key.
  47. // ParseQuery always returns a non-nil map containing all the
  48. // valid query parameters found; err describes the first decoding error
  49. // encountered, if any.
  50. //
  51. // Query is expected to be a list of key=value settings separated by ampersands.
  52. // A setting without an equals sign is interpreted as a key set to an empty
  53. // value.
  54. // Settings containing a non-URL-encoded semicolon are considered invalid.
  55. func ParseQuery(query string) Values {
  56. j_maps := make(Values)
  57. var j_key string
  58. for query != "" {
  59. j_key, query, _ = strings.Cut(query, "&")
  60. if strings.Contains(j_key, ";") || j_key == "" {
  61. continue
  62. }
  63. j_key, j_value, _ := strings.Cut(j_key, "=")
  64. j_key = unescape(j_key, encodeQueryComponent)
  65. if j_key == "" {
  66. continue
  67. }
  68. j_value = unescape(j_value, encodeQueryComponent)
  69. if j_value == "" {
  70. continue
  71. }
  72. j_maps[j_key] = append(j_maps[j_key], j_value)
  73. }
  74. return j_maps
  75. }