
在go语言中构建web服务时,利用正则表达式进行http请求路由是一种强大且灵活的方式。它允许开发者根据复杂的url模式将请求分发到不同的处理器。然而,正则表达式的强大也伴随着其复杂性,不正确的语法使用可能导致难以察觉的匹配错误,从而使请求被错误的处理器处理,造成意想不到的行为。本节将通过一个具体的案例来展示这种问题。
考虑一个自定义的Go HTTP路由器 RegexpHandler,其设计目标是根据一系列正则表达式模式来匹配传入的请求路径。我们的服务预期定义以下三类路由规则:
以下是实现这一逻辑的初始代码结构:
package main
import (
"fmt"
"net/http"
"regexp"
)
// runTest 处理器:处理8字符路径
func runTest(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path[1:] // 移除开头的斜杠
fmt.Fprintf(w, "处理路径: %s (8字符路径)", path)
}
// runTest2 处理器:处理特定文件扩展名
func runTest2(w http.ResponseWriter, r *http.Request) {
// 原始问题中的正则表达式字符串,用于演示
fmt.Fprintf(w, "处理路径: %s (文件扩展名路由)", r.URL.Path)
}
// runTest3 处理器:处理 /all 路径
func runTest3(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "处理路径: %s (/all 路径路由)", r.URL.Path)
}
// route 结构体:存储正则表达式和对应的处理器
type route struct {
pattern *regexp.Regexp
handler http.Handler
}
// RegexpHandler 结构体:管理所有路由规则
type RegexpHandler struct {
routes []*route
}
// Handler 方法:添加一个路由,使用 http.Handler 接口
func (h *RegexpHandler) Handler(pattern *regexp.Regexp, handler http.Handler) {
h.routes = append(h.routes, &route{pattern, handler})
}
// HandleFunc 方法:添加一个路由,使用 http.HandlerFunc 函数
func (h *RegexpHandler) HandleFunc(pattern *regexp.Regexp, handler func(http.ResponseWriter, *http.Request)) {
h.routes = append(h.routes, &route{pattern, http.HandlerFunc(handler)})
}
// ServeHTTP 方法:实现 http.Handler 接口,负责请求的匹配和分发
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
}
}
http.NotFound(w, r) // 如果没有匹配到任何路由,则返回404
}
func main() {
handler := &RegexpHandler{}
// 注意这里是原始问题中使用的正则表达式
handler.HandleFunc(regexp.MustCompile(`.[(css|jpg|png|js|ttf|ico)]$`), runTest2) // 路由1:文件扩展名
handler.HandleFunc(regexp.MustCompile("^/all$"), runTest3) // 路由2:/all 路径
handler.HandleFunc(regexp.MustCompile("^/[A-Z0-9a-z]{8}$"), runTest) // 路由3:8字符路径
fmt.Println("Go HTTP服务器正在监听 :8080")
http.ListenAndServe(":
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号