group.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package wisp
  2. import (
  3. "net/http"
  4. "path"
  5. "slices"
  6. "strings"
  7. )
  8. type Group struct {
  9. prefix string
  10. parent *Wisp
  11. middlewares []Middleware
  12. }
  13. func (g *Group) Use(m ...Middleware) {
  14. g.middlewares = append(g.middlewares, m...)
  15. }
  16. func (g *Group) GET(path string, h Handler, mws ...Middleware) {
  17. g.handle(http.MethodGet, path, h, mws...)
  18. }
  19. func (g *Group) POST(path string, h Handler, mws ...Middleware) {
  20. g.handle(http.MethodPost, path, h, mws...)
  21. }
  22. func (g *Group) PUT(path string, h Handler, mws ...Middleware) {
  23. g.handle(http.MethodPut, path, h, mws...)
  24. }
  25. func (g *Group) DELETE(path string, h Handler, mws ...Middleware) {
  26. g.handle(http.MethodDelete, path, h, mws...)
  27. }
  28. func (g *Group) PATCH(path string, h Handler, mws ...Middleware) {
  29. g.handle(http.MethodPatch, path, h, mws...)
  30. }
  31. func (g *Group) OPTIONS(path string, h Handler, mws ...Middleware) {
  32. g.handle(http.MethodOptions, path, h, mws...)
  33. }
  34. func (g *Group) HEAD(path string, h Handler, mws ...Middleware) {
  35. g.handle(http.MethodHead, path, h, mws...)
  36. }
  37. func (g *Group) Static(relativePath, root string) {
  38. if !strings.HasPrefix(relativePath, "/") {
  39. relativePath = "/" + relativePath
  40. }
  41. fullPath := path.Join(g.prefix, relativePath)
  42. fileServer := http.StripPrefix(fullPath, http.FileServer(http.Dir(root)))
  43. handler := func(ctx *Context) error {
  44. fileServer.ServeHTTP(ctx.Response(), ctx.Request())
  45. return nil
  46. }
  47. g.GET(relativePath+"/*filepath", handler)
  48. }
  49. func (g *Group) handle(method, path string, h Handler, routeMws ...Middleware) {
  50. allMws := slices.Clone(g.parent.middlewares)
  51. allMws = append(allMws, g.middlewares...)
  52. allMws = append(allMws, routeMws...)
  53. h = g.parent.chainMiddlewares(h, allMws)
  54. fullPath := g.prefix + path
  55. finalHandler := g.parent.makeHTTPRouterHandler(h)
  56. switch method {
  57. case http.MethodGet:
  58. g.parent.router.GET(fullPath, finalHandler)
  59. case http.MethodPost:
  60. g.parent.router.POST(fullPath, finalHandler)
  61. case http.MethodPut:
  62. g.parent.router.PUT(fullPath, finalHandler)
  63. case http.MethodDelete:
  64. g.parent.router.DELETE(fullPath, finalHandler)
  65. case http.MethodPatch:
  66. g.parent.router.PATCH(fullPath, finalHandler)
  67. case http.MethodOptions:
  68. g.parent.router.OPTIONS(fullPath, finalHandler)
  69. case http.MethodHead:
  70. g.parent.router.HEAD(fullPath, finalHandler)
  71. }
  72. }