gitea

Development moved to Codeberg

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 62
  63. 63
  64. 64
  65. 65
  66. 66
  67. 67
  68. 68
  69. 69
  70. 70
  71. 71
  72. 72
package middleware

import (
	"context"
	"net/http"
	"strings"

	"github.com/go-chi/chi/v5"
)

var (
	// URLFormatCtxKey is the context.Context key to store the URL format data
	// for a request.
	URLFormatCtxKey = &contextKey{"URLFormat"}
)

// URLFormat is a middleware that parses the url extension from a request path and stores it
// on the context as a string under the key `middleware.URLFormatCtxKey`. The middleware will
// trim the suffix from the routing path and continue routing.
//
// Routers should not include a url parameter for the suffix when using this middleware.
//
// Sample usage.. for url paths: `/articles/1`, `/articles/1.json` and `/articles/1.xml`
//
//  func routes() http.Handler {
//    r := chi.NewRouter()
//    r.Use(middleware.URLFormat)
//
//    r.Get("/articles/{id}", ListArticles)
//
//    return r
//  }
//
//  func ListArticles(w http.ResponseWriter, r *http.Request) {
// 	  urlFormat, _ := r.Context().Value(middleware.URLFormatCtxKey).(string)
//
// 	  switch urlFormat {
// 	  case "json":
// 	  	render.JSON(w, r, articles)
// 	  case "xml:"
// 	  	render.XML(w, r, articles)
// 	  default:
// 	  	render.JSON(w, r, articles)
// 	  }
// }
//
func URLFormat(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()

		var format string
		path := r.URL.Path

		if strings.Index(path, ".") > 0 {
			base := strings.LastIndex(path, "/")
			idx := strings.LastIndex(path[base:], ".")

			if idx > 0 {
				idx += base
				format = path[idx+1:]

				rctx := chi.RouteContext(r.Context())
				rctx.RoutePath = path[:idx]
			}
		}

		r = r.WithContext(context.WithValue(ctx, URLFormatCtxKey, format))

		next.ServeHTTP(w, r)
	}
	return http.HandlerFunc(fn)
}