使用自訂處理程序與通配符進行高級處理程序模式匹配
當使用http.HandleFunc 在Go 中定義路由模式時,內建機制不提供通配符支援。這可能是捕獲動態 URL 元件的限制因素。
具有正則表達式模式匹配的自定義處理程序
要克服此限制,可以創建一個自定義處理程序支持使用正則表達式的靈活模式匹配。這是一個範例:
import ( "net/http" "regexp" ) type route struct { pattern *regexp.Regexp handler http.Handler } type RegexpHandler struct { routes []*route } // Handler adds a route to the custom handler. func (h *RegexpHandler) Handler(pattern *regexp.Regexp, handler http.Handler) { h.routes = append(h.routes, &route{pattern, handler}) } // HandleFunc adds a function-based route to the custom handler. func (h *RegexpHandler) HandleFunc(pattern *regexp.Regexp, handler func(http.ResponseWriter, *http.Request)) { h.routes = append(h.routes, &route{pattern, http.HandlerFunc(handler)}) } // ServeHTTP iterates through registered routes and checks if any pattern matches the request. If a match is found, the corresponding handler is invoked. func (h *RegexpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { for _, route := range h.routes { if route.pattern.MatchString(r.URL.Path) { route.handler.ServeHTTP(w, r) return } } // No pattern matched, return a 404 response. http.NotFound(w, r) }
用法:
自訂處理程序處理具有通配符模式的 URL 的範例用法:
import ( "log" "net/http" ) func main() { rh := &RegexpHandler{} // Define a regular expression for capturing any valid URL string. pattern := regexp.MustCompile(`/groups/.*/people`) rh.HandleFunc(pattern, peopleInGroupHandler) // Start the web server and use the custom handler. log.Fatal(http.ListenAndServe(":8080", rh)) }
這種方法可讓您建立超出 http.HandleFunc 限制的靈活路由模式,同時保持對自訂處理程序中路徑匹配邏輯的控制。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3