utils.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package desktop
  2. import (
  3. "encoding/json"
  4. "regexp"
  5. "strings"
  6. )
  7. type MatchResult struct {
  8. Params map[string]string `json:"params"`
  9. Match bool `json:"match"`
  10. Origin string `json:"origin"`
  11. Pattern string `json:"pattern"`
  12. }
  13. func (r *MatchResult) String() string {
  14. b, err := json.Marshal(r)
  15. if err != nil {
  16. return ""
  17. }
  18. return string(b)
  19. }
  20. func (r *MatchResult) GetParam(key string) string {
  21. return r.Params[key]
  22. }
  23. func ParseKey(pattern string) string {
  24. index := strings.Index(pattern, "/:")
  25. if index < 0 || index > len(pattern)-2 {
  26. return ""
  27. }
  28. str := pattern[index+1:]
  29. end := strings.Index(str, "/")
  30. if end == -1 {
  31. end = len(str)
  32. }
  33. key := str[0:end]
  34. return key
  35. }
  36. // ParsePathParam 解析路径中的 :id 字段
  37. func ParsePathParam(path string, pattern string) *MatchResult {
  38. var result = &MatchResult{
  39. Match: false,
  40. Params: map[string]string{},
  41. Origin: path,
  42. }
  43. var keys []string
  44. var reg = pattern
  45. for i := 0; true; i++ {
  46. key := ParseKey(reg)
  47. if len(key) == 0 {
  48. break
  49. }
  50. keys = append(keys, key[1:])
  51. reg = strings.ReplaceAll(reg, key, "(.+)?")
  52. }
  53. result.Pattern = reg
  54. compile := regexp.MustCompile(reg)
  55. match := compile.FindStringSubmatch(path)
  56. if len(match) < 1 {
  57. return result
  58. }
  59. result.Match = true
  60. for i := 1; i < len(match); i++ {
  61. k := keys[i-1]
  62. result.Params[k] = match[i]
  63. }
  64. return result
  65. }