apiserv.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. package apiserv
  2. import (
  3. "net/http"
  4. "regexp"
  5. "strings"
  6. "github.com/vladimirok5959/golang-utils/utils/http/logger"
  7. )
  8. var mParam = regexp.MustCompile(`\{([^/]*)}`)
  9. var mParams = &Params{
  10. list: map[*http.Request][]Param{},
  11. }
  12. type ServeMux struct {
  13. handlers *Handlers
  14. }
  15. func NewServeMux() *ServeMux {
  16. s := ServeMux{
  17. handlers: &Handlers{
  18. list: map[*regexp.Regexp]Handler{},
  19. },
  20. }
  21. return &s
  22. }
  23. func GetParams(r *http.Request) []Param {
  24. mParams.Lock()
  25. defer mParams.Unlock()
  26. if v, ok := mParams.list[r]; ok {
  27. return v
  28. }
  29. return []Param{}
  30. }
  31. func (s ServeMux) regexp(pattern string) string {
  32. pattern = strings.ReplaceAll(pattern, "-", "\\-")
  33. pattern = strings.ReplaceAll(pattern, ".", "\\.")
  34. pattern = strings.ReplaceAll(pattern, "/", "\\/")
  35. pattern = mParam.ReplaceAllStringFunc(pattern, func(str string) string {
  36. if str == "{i}" {
  37. return "([\\d]+)"
  38. } else if str == "{s}" {
  39. return "([^\\/]+)"
  40. }
  41. return str
  42. })
  43. return "(?i)^" + pattern + "$"
  44. }
  45. func (s ServeMux) Delete(pattern string, handler http.Handler) {
  46. s.Handle(pattern, []string{http.MethodDelete}, handler)
  47. }
  48. func (s ServeMux) Get(pattern string, handler http.Handler) {
  49. s.Handle(pattern, []string{http.MethodGet}, handler)
  50. }
  51. func (s ServeMux) Handle(pattern string, methods []string, handler http.Handler) {
  52. s.handlers.Lock()
  53. defer s.handlers.Unlock()
  54. if pattern != "" {
  55. re := regexp.MustCompile(s.regexp(pattern))
  56. s.handlers.list[re] = Handler{
  57. handler: handler,
  58. methods: methods,
  59. }
  60. } else {
  61. s.handlers.list[nil] = Handler{
  62. handler: handler,
  63. methods: methods,
  64. }
  65. }
  66. }
  67. func (s ServeMux) NotFound(handler http.Handler) {
  68. s.Handle("", []string{http.MethodGet}, handler)
  69. }
  70. func (s ServeMux) Options(pattern string, handler http.Handler) {
  71. s.Handle(pattern, []string{http.MethodOptions}, handler)
  72. }
  73. func (s ServeMux) Patch(pattern string, handler http.Handler) {
  74. s.Handle(pattern, []string{http.MethodPatch}, handler)
  75. }
  76. func (s ServeMux) Post(pattern string, handler http.Handler) {
  77. s.Handle(pattern, []string{http.MethodPost}, handler)
  78. }
  79. func (s ServeMux) Put(pattern string, handler http.Handler) {
  80. s.Handle(pattern, []string{http.MethodPut}, handler)
  81. }
  82. func (s ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  83. s.handlers.Lock()
  84. defer s.handlers.Unlock()
  85. for re, h := range s.handlers.list {
  86. if re != nil && re.Match([]byte(r.URL.Path)) {
  87. if h.IsMethod(r.Method) {
  88. if rs := re.FindAllStringSubmatch(r.URL.Path, 1); len(rs) >= 1 {
  89. defer func() {
  90. mParams.Lock()
  91. delete(mParams.list, r)
  92. defer mParams.Unlock()
  93. }()
  94. mParams.Lock()
  95. for _, p := range rs[0] {
  96. if _, ok := mParams.list[r]; !ok {
  97. mParams.list[r] = []Param{{value: p}}
  98. } else {
  99. mParams.list[r] = append(mParams.list[r], Param{value: p})
  100. }
  101. select {
  102. case <-r.Context().Done():
  103. mParams.Unlock()
  104. return
  105. default:
  106. }
  107. }
  108. mParams.Unlock()
  109. }
  110. select {
  111. case <-r.Context().Done():
  112. return
  113. default:
  114. }
  115. logger.LogRequests(h.handler).ServeHTTP(w, r)
  116. return
  117. } else {
  118. w.WriteHeader(http.StatusMethodNotAllowed)
  119. return
  120. }
  121. }
  122. select {
  123. case <-r.Context().Done():
  124. return
  125. default:
  126. }
  127. }
  128. // Error 404
  129. if h, ok := s.handlers.list[nil]; ok {
  130. logger.LogRequests(h.handler).ServeHTTP(w, r)
  131. return
  132. }
  133. w.WriteHeader(http.StatusNotFound)
  134. }