url.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package pq
  2. import (
  3. "fmt"
  4. "net"
  5. nurl "net/url"
  6. "sort"
  7. "strings"
  8. )
  9. // ParseURL no longer needs to be used by clients of this library since supplying a URL as a
  10. // connection string to sql.Open() is now supported:
  11. //
  12. // sql.Open("postgres", "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full")
  13. //
  14. // It remains exported here for backwards-compatibility.
  15. //
  16. // ParseURL converts a url to a connection string for driver.Open.
  17. // Example:
  18. //
  19. // "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full"
  20. //
  21. // converts to:
  22. //
  23. // "user=bob password=secret host=1.2.3.4 port=5432 dbname=mydb sslmode=verify-full"
  24. //
  25. // A minimal example:
  26. //
  27. // "postgres://"
  28. //
  29. // This will be blank, causing driver.Open to use all of the defaults
  30. func ParseURL(url string) (string, error) {
  31. u, err := nurl.Parse(url)
  32. if err != nil {
  33. return "", err
  34. }
  35. if u.Scheme != "postgres" && u.Scheme != "postgresql" {
  36. return "", fmt.Errorf("invalid connection protocol: %s", u.Scheme)
  37. }
  38. var kvs []string
  39. escaper := strings.NewReplacer(` `, `\ `, `'`, `\'`, `\`, `\\`)
  40. accrue := func(k, v string) {
  41. if v != "" {
  42. kvs = append(kvs, k+"="+escaper.Replace(v))
  43. }
  44. }
  45. if u.User != nil {
  46. v := u.User.Username()
  47. accrue("user", v)
  48. v, _ = u.User.Password()
  49. accrue("password", v)
  50. }
  51. if host, port, err := net.SplitHostPort(u.Host); err != nil {
  52. accrue("host", u.Host)
  53. } else {
  54. accrue("host", host)
  55. accrue("port", port)
  56. }
  57. if u.Path != "" {
  58. accrue("dbname", u.Path[1:])
  59. }
  60. q := u.Query()
  61. for k := range q {
  62. accrue(k, q.Get(k))
  63. }
  64. sort.Strings(kvs) // Makes testing easier (not a performance concern)
  65. return strings.Join(kvs, " "), nil
  66. }