url.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package httptoo
  2. import (
  3. "net/http"
  4. "net/url"
  5. )
  6. // Deep copies a URL. I could call it DeepCopyURL, but what else would you be
  7. // copying when you have a *url.URL? Of note is that the Userinfo is deep
  8. // copied. The returned URL shares no references with the original.
  9. func CopyURL(u *url.URL) (ret *url.URL) {
  10. ret = new(url.URL)
  11. *ret = *u
  12. if u.User != nil {
  13. ret.User = new(url.Userinfo)
  14. *ret.User = *u.User
  15. }
  16. return
  17. }
  18. // Reconstructs the URL that would have produced the given Request.
  19. // Request.URLs are not fully populated in http.Server handlers.
  20. func RequestedURL(r *http.Request) (ret *url.URL) {
  21. ret = CopyURL(r.URL)
  22. ret.Host = r.Host
  23. ret.Scheme = OriginatingProtocol(r)
  24. return
  25. }
  26. // The official URL struct parameters, for tracking changes and reference
  27. // here.
  28. //
  29. // Scheme string
  30. // Opaque string // encoded opaque data
  31. // User *Userinfo // username and password information
  32. // Host string // host or host:port
  33. // Path string
  34. // RawPath string // encoded path hint (Go 1.5 and later only; see EscapedPath method)
  35. // ForceQuery bool // append a query ('?') even if RawQuery is empty
  36. // RawQuery string // encoded query values, without '?'
  37. // Fragment string // fragment for references, without '#'
  38. // Return the first URL extended with elements of the second, in the manner
  39. // that occurs throughout my projects. Noteworthy difference from
  40. // url.URL.ResolveReference is that if the reference has a scheme, the base is
  41. // not completely ignored.
  42. func AppendURL(u, v *url.URL) *url.URL {
  43. u = CopyURL(u)
  44. clobberString(&u.Scheme, v.Scheme)
  45. clobberString(&u.Host, v.Host)
  46. u.Path += v.Path
  47. q := u.Query()
  48. for k, v := range v.Query() {
  49. q[k] = append(q[k], v...)
  50. }
  51. u.RawQuery = q.Encode()
  52. return u
  53. }
  54. func clobberString(s *string, value string) {
  55. if value != "" {
  56. *s = value
  57. }
  58. }