url_format.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package middleware
  2. import (
  3. "context"
  4. "net/http"
  5. "strings"
  6. "github.com/go-chi/chi/v5"
  7. )
  8. var (
  9. // URLFormatCtxKey is the context.Context key to store the URL format data
  10. // for a request.
  11. URLFormatCtxKey = &contextKey{"URLFormat"}
  12. )
  13. // URLFormat is a middleware that parses the url extension from a request path and stores it
  14. // on the context as a string under the key `middleware.URLFormatCtxKey`. The middleware will
  15. // trim the suffix from the routing path and continue routing.
  16. //
  17. // Routers should not include a url parameter for the suffix when using this middleware.
  18. //
  19. // Sample usage for url paths `/articles/1`, `/articles/1.json` and `/articles/1.xml`:
  20. //
  21. // func routes() http.Handler {
  22. // r := chi.NewRouter()
  23. // r.Use(middleware.URLFormat)
  24. //
  25. // r.Get("/articles/{id}", ListArticles)
  26. //
  27. // return r
  28. // }
  29. //
  30. // func ListArticles(w http.ResponseWriter, r *http.Request) {
  31. // urlFormat, _ := r.Context().Value(middleware.URLFormatCtxKey).(string)
  32. //
  33. // switch urlFormat {
  34. // case "json":
  35. // render.JSON(w, r, articles)
  36. // case "xml:"
  37. // render.XML(w, r, articles)
  38. // default:
  39. // render.JSON(w, r, articles)
  40. // }
  41. // }
  42. func URLFormat(next http.Handler) http.Handler {
  43. fn := func(w http.ResponseWriter, r *http.Request) {
  44. ctx := r.Context()
  45. var format string
  46. path := r.URL.Path
  47. rctx := chi.RouteContext(r.Context())
  48. if rctx != nil && rctx.RoutePath != "" {
  49. path = rctx.RoutePath
  50. }
  51. if strings.Index(path, ".") > 0 {
  52. base := strings.LastIndex(path, "/")
  53. idx := strings.LastIndex(path[base:], ".")
  54. if idx > 0 {
  55. idx += base
  56. format = path[idx+1:]
  57. if rctx != nil {
  58. rctx.RoutePath = path[:idx]
  59. }
  60. }
  61. }
  62. r = r.WithContext(context.WithValue(ctx, URLFormatCtxKey, format))
  63. next.ServeHTTP(w, r)
  64. }
  65. return http.HandlerFunc(fn)
  66. }