prefix_cut.go 672 B

1234567891011121314151617181920212223
  1. package http_middleware
  2. import (
  3. "net/http"
  4. "strings"
  5. )
  6. // 请求前缀剪裁中间件(底层http.Handler接口织入,非Gin中间件)
  7. type PrefixCut struct {
  8. Handler http.Handler
  9. HostPrefix string
  10. }
  11. func (cut *PrefixCut) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
  12. if len(strings.TrimSpace(cut.HostPrefix)) > 0 {
  13. hostPrefixPattern := getHostPrefixPattern(cut.HostPrefix)
  14. if hostPrefixPattern.MatchString(request.URL.Path) {
  15. request.URL.Path = hostPrefixPattern.ReplaceAllString(request.URL.Path, "")
  16. request.RequestURI = hostPrefixPattern.ReplaceAllString(request.RequestURI, "")
  17. }
  18. }
  19. cut.Handler.ServeHTTP(writer, request)
  20. }