dsn.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package dsn
  2. import (
  3. "errors"
  4. "strings"
  5. )
  6. var (
  7. errInvalidDSN = errors.New("invalid dsn params")
  8. )
  9. // DSN is a configuration parsed from a DSN string
  10. // key:secret@group/topic=?&role=?
  11. type DSN struct {
  12. Key string // app key
  13. Secret string // app secret
  14. Group string // kafka group
  15. Topic string // kafka topic
  16. Role string // pub or sub
  17. Color string // env color
  18. }
  19. // ParseDSN parse databus info.
  20. func ParseDSN(s string) (*DSN, error) {
  21. if strings.Count(s, "@") != 1 || strings.Count(s, "/") != 1 || strings.Count(s, ":") != 1 {
  22. return nil, errInvalidDSN
  23. }
  24. var (
  25. c = &DSN{}
  26. params string
  27. )
  28. i := len(s) - 1
  29. var j, k int
  30. for j = i; j >= 0; j-- {
  31. // found key:passwd
  32. if s[j] == '@' {
  33. for k = 0; k < j; k++ {
  34. if s[k] == ':' {
  35. c.Secret = s[k+1 : j]
  36. break
  37. }
  38. }
  39. c.Key = s[:k]
  40. break
  41. }
  42. }
  43. // group
  44. for k = j + 1; k < i; k++ {
  45. if s[k] == '/' {
  46. break
  47. }
  48. }
  49. c.Group = s[j+1 : k]
  50. params = s[k+1:]
  51. for _, v := range strings.Split(params, "&") {
  52. param := strings.SplitN(v, "=", 2)
  53. if len(param) != 2 {
  54. continue
  55. }
  56. switch value := param[1]; strings.ToLower(param[0]) {
  57. case "topic":
  58. c.Topic = value
  59. case "role":
  60. c.Role = value
  61. case "color":
  62. c.Color = value
  63. }
  64. }
  65. return c, nil
  66. }