func changePath(req *http.Request, newVal func(pathOrRawPath string) string) {
	req.URL.RawPath = newVal(req.URL.RawPath)
	if p, err := url.PathUnescape(req.URL.RawPath); err == nil && p != "" {
		req.URL.Path = p
	} else {
		req.URL.Path = newVal(req.URL.Path)
	}
}
changePath updates the path on the request URL. It first executes newVal on
req.URL.RawPath, and if the result is a valid escaping, it will be copied
into req.URL.Path; otherwise newVal is evaluated only on req.URL.Path.
package rewrite
import (
	"fmt"
	"net/http"
	"net/url"
	"regexp"
	"strconv"
	"strings"
	"github.com/caddyserver/caddy/v2"
	"github.com/caddyserver/caddy/v2/modules/caddyhttp"
	"go.uber.org/zap"
)
func init() {
	caddy.RegisterModule(Rewrite{})
}
type Rewrite struct {
	Method string `json:"method,omitempty"`
	URI string `json:"uri,omitempty"`
	StripPathPrefix string `json:"strip_path_prefix,omitempty"`
	StripPathSuffix string `json:"strip_path_suffix,omitempty"`
	URISubstring []substrReplacer `json:"uri_substring,omitempty"`
	PathRegexp []*regexReplacer `json:"path_regexp,omitempty"`
	logger *zap.Logger
}
func (Rewrite) CaddyModule() caddy.ModuleInfo {
	return caddy.ModuleInfo{
		ID:  "http.handlers.rewrite",
		New: func() caddy.Module { return new(Rewrite) },
	}
}
func (rewr *Rewrite) Provision(ctx caddy.Context) error {
	rewr.logger = ctx.Logger(rewr)
	for i, rep := range rewr.PathRegexp {
		if rep.Find == "" {
			return fmt.Errorf("path_regexp find cannot be empty")
		}
		re, err := regexp.Compile(rep.Find)
		if err != nil {
			return fmt.Errorf("compiling regular expression %d: %v", i, err)
		}
		rep.re = re
	}
	return nil
}
func (rewr Rewrite) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
	repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
	logger := rewr.logger.With(
		zap.Object("request", caddyhttp.LoggableHTTPRequest{Request: r}),
	)
	changed := rewr.rewrite(r, repl, logger)
	if changed {
		logger.Debug("rewrote request",
			zap.String("method", r.Method),
			zap.String("uri", r.RequestURI),
		)
	}
	return next.ServeHTTP(w, r)
}
func (rewr Rewrite) rewrite(r *http.Request, repl *caddy.Replacer, logger *zap.Logger) bool {
	oldMethod := r.Method
	oldURI := r.RequestURI
	if rewr.Method != "" {
		r.Method = strings.ToUpper(repl.ReplaceAll(rewr.Method, ""))
	}
	if uri := rewr.URI; uri != "" {
		pathStart, qsStart, fragStart := -1, -1, -1
		pathEnd, qsEnd := -1, -1
		for i, ch := range uri {
			switch {
			case ch == '?' && qsStart < 0:
				pathEnd, qsStart = i, i+1
			case ch == '#' && fragStart < 0:
				qsEnd, fragStart = i, i+1
			case pathStart < 0 && qsStart < 0 && fragStart < 0:
				pathStart = i
			}
		}
		if pathStart >= 0 && pathEnd < 0 {
			pathEnd = len(uri)
		}
		if qsStart >= 0 && qsEnd < 0 {
			qsEnd = len(uri)
		}
		var path, query, frag string
		if pathStart > -1 {
			path = uri[pathStart:pathEnd]
		}
		if qsStart > -1 {
			query = uri[qsStart:qsEnd]
		}
		if fragStart > -1 {
			frag = uri[fragStart:]
		}
		var newPath, newQuery, newFrag string
		if path != "" {
			newPath = repl.ReplaceAll(path, "")
		}
		if quPos := strings.Index(newPath, "?"); quPos > -1 {
			var injectedQuery string
			newPath, injectedQuery = newPath[:quPos], newPath[quPos+1:]
			if query == "" {
				query = injectedQuery
			}
		}
		if query != "" {
			newQuery = buildQueryString(query, repl)
		}
		if frag != "" {
			newFrag = repl.ReplaceAll(frag, "")
		}
		if pathStart >= 0 {
			r.URL.Path = newPath
		}
		if qsStart >= 0 {
			r.URL.RawQuery = newQuery
		}
		if fragStart >= 0 {
			r.URL.Fragment = newFrag
		}
	}
	if rewr.StripPathPrefix != "" {
		prefix := repl.ReplaceAll(rewr.StripPathPrefix, "")
		r.URL.RawPath = strings.TrimPrefix(r.URL.RawPath, prefix)
		if p, err := url.PathUnescape(r.URL.RawPath); err == nil && p != "" {
			r.URL.Path = p
		} else {
			r.URL.Path = strings.TrimPrefix(r.URL.Path, prefix)
		}
	}
	if rewr.StripPathSuffix != "" {
		suffix := repl.ReplaceAll(rewr.StripPathSuffix, "")
		changePath(r, func(pathOrRawPath string) string {
			return strings.TrimSuffix(pathOrRawPath, suffix)
		})
	}
	for _, rep := range rewr.URISubstring {
		rep.do(r, repl)
	}
	for _, rep := range rewr.PathRegexp {
		rep.do(r, repl)
	}
	r.RequestURI = r.URL.RequestURI()
	return r.Method != oldMethod || r.RequestURI != oldURI
}
func buildQueryString(qs string, repl *caddy.Replacer) string {
	var sb strings.Builder
	wroteVal := true
	for len(qs) > 0 {
		nextEq, nextAmp := strings.Index(qs, "="), strings.Index(qs, "&")
		ampIsNext := nextAmp >= 0 && (nextAmp < nextEq || nextEq < 0)
		end := len(qs)  
		if ampIsNext {
			end = nextAmp  
		} else if nextEq >= 0 && (nextEq < nextAmp || nextAmp < 0) {
			end = nextEq  
		}
		comp := qs[:end]
		comp, _ = repl.ReplaceFunc(comp, func(name string, val interface{}) (interface{}, error) {
			if name == "http.request.uri.query" && wroteVal {
				return val, nil  
			}
			var valStr string
			switch v := val.(type) {
			case string:
				valStr = v
			case fmt.Stringer:
				valStr = v.String()
			case int:
				valStr = strconv.Itoa(v)
			default:
				valStr = fmt.Sprintf("%+v", v)
			}
			return url.QueryEscape(valStr), nil
		})
		if end < len(qs) {
			end++  
		}
		qs = qs[end:]
		if wroteVal {
			if sb.Len() > 0 && len(comp) > 0 {
				sb.WriteRune('&')
			}
		} else {
			sb.WriteRune('=')
		}
		sb.WriteString(comp)
		wroteVal = ampIsNext
	}
	return sb.String()
}
type substrReplacer struct {
	Find string `json:"find,omitempty"`
	Replace string `json:"replace,omitempty"`
	Limit int `json:"limit,omitempty"`
}
func (rep substrReplacer) do(r *http.Request, repl *caddy.Replacer) {
	if rep.Find == "" {
		return
	}
	lim := rep.Limit
	if lim == 0 {
		lim = -1
	}
	find := repl.ReplaceAll(rep.Find, "")
	replace := repl.ReplaceAll(rep.Replace, "")
	changePath(r, func(pathOrRawPath string) string {
		return strings.Replace(pathOrRawPath, find, replace, lim)
	})
	r.URL.RawQuery = strings.Replace(r.URL.RawQuery, find, replace, lim)
}
type regexReplacer struct {
	Find string `json:"find,omitempty"`
	Replace string `json:"replace,omitempty"`
	re *regexp.Regexp
}
func (rep regexReplacer) do(r *http.Request, repl *caddy.Replacer) {
	if rep.Find == "" || rep.re == nil {
		return
	}
	replace := repl.ReplaceAll(rep.Replace, "")
	changePath(r, func(pathOrRawPath string) string {
		return rep.re.ReplaceAllString(pathOrRawPath, replace)
	})
}