/vendor/github.com/webx-top/echo/host.go

https://github.com/admpub/nging · Go · 111 lines · 104 code · 7 blank · 0 comment · 5 complexity · 5b17eeb81174db6cfc4734114d0e395f MD5 · raw file

  1. package echo
  2. import (
  3. "fmt"
  4. "regexp"
  5. )
  6. type Hoster interface {
  7. Name() string
  8. Alias() string
  9. Format(args ...interface{}) string
  10. FormatMap(params H) string
  11. RegExp() *regexp.Regexp
  12. Match(host string) (r []string, hasExpr bool)
  13. }
  14. type host struct {
  15. name string
  16. alias string
  17. format string
  18. regExp *regexp.Regexp
  19. names []string
  20. }
  21. func (h *host) Name() string {
  22. return h.name
  23. }
  24. func (h *host) Alias() string {
  25. return h.alias
  26. }
  27. func (h *host) Format(args ...interface{}) string {
  28. if len(args) > 0 {
  29. return fmt.Sprintf(h.format, args...)
  30. }
  31. return h.format
  32. }
  33. func (h *host) FormatMap(params H) string {
  34. if len(params) > 0 {
  35. args := make([]interface{}, len(h.names))
  36. for index, name := range h.names {
  37. v, y := params[name]
  38. if y {
  39. args[index] = v
  40. } else {
  41. args[index] = ``
  42. }
  43. }
  44. return fmt.Sprintf(h.format, args...)
  45. }
  46. return h.format
  47. }
  48. func (h *host) RegExp() *regexp.Regexp {
  49. return h.regExp
  50. }
  51. func (h *host) Match(host string) (r []string, hasExpr bool) {
  52. if h.regExp != nil {
  53. match := h.regExp.FindStringSubmatch(host)
  54. if len(match) > 0 {
  55. return match[1:], true
  56. }
  57. return nil, true
  58. }
  59. return nil, false
  60. }
  61. func NewHost(name string) *host {
  62. return &host{name: name}
  63. }
  64. var hostRegExp = regexp.MustCompile(`<([^:]+)(?:\:(.+?))?>`)
  65. func (h *host) Parse() *host {
  66. matches := hostRegExp.FindAllStringSubmatchIndex(h.name, -1)
  67. if len(matches) == 0 {
  68. return h
  69. }
  70. var format string
  71. var regExpr string
  72. var lastPosition int
  73. for _, matchIndex := range matches {
  74. if matchIndex[0] > 0 {
  75. v := h.name[lastPosition:matchIndex[0]]
  76. format += v
  77. regExpr += regexp.QuoteMeta(v)
  78. }
  79. lastPosition = matchIndex[1]
  80. format += `%v`
  81. name := h.name[matchIndex[2]:matchIndex[3]]
  82. if matchIndex[4] > 0 {
  83. regExpr += `(` + h.name[matchIndex[4]:matchIndex[5]] + `)`
  84. } else {
  85. regExpr += `([^.]+)`
  86. }
  87. h.names = append(h.names, name)
  88. }
  89. if lastPosition > 0 {
  90. if lastPosition < len(h.name) {
  91. v := h.name[lastPosition:]
  92. format += v
  93. regExpr += regexp.QuoteMeta(v)
  94. }
  95. }
  96. h.format = format
  97. h.regExp = regexp.MustCompile(`^` + regExpr + `$`)
  98. return h
  99. }