partialURL.go 1010 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package template
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. type PartialURL struct {
  7. Path string
  8. Query map[string]string
  9. }
  10. func LowercaseFirstChar(s string) string {
  11. return strings.ToLower(s[0:1]) + s[1:]
  12. }
  13. // Turn `url` into /path?other_key=other_value&`key`=
  14. func UnfinishedQuery(url PartialURL, key string) string {
  15. result := fmt.Sprintf("/%s", url.Path)
  16. first_query_pair := true
  17. for k, v := range url.Query {
  18. k = LowercaseFirstChar(k)
  19. if k == key {
  20. continue
  21. }
  22. if v == "" {
  23. // If the value is empty, ignore to not clutter the URL
  24. continue
  25. }
  26. if first_query_pair {
  27. result += "?"
  28. first_query_pair = false
  29. } else {
  30. result += "&"
  31. }
  32. result += fmt.Sprintf("%s=%s", k, v)
  33. }
  34. // This is to move the matched query to the end of the URL
  35. var t string
  36. if first_query_pair {
  37. t = "?"
  38. } else {
  39. t = "&"
  40. }
  41. result += fmt.Sprintf("%s%s=", t, key)
  42. return result
  43. }
  44. func ReplaceQuery(url PartialURL, key string, value string) string {
  45. return UnfinishedQuery(url, key) + value
  46. }