我正在尝试为我的路由器使用标准的Go http软件包。
在我的main.go中,它开始:
func main() {
mux := http.NewServeMux()
fs := http.FileServer(http.Dir("static"))
handler := http.StripPrefix("/static/", fs)
mux.Handle("/static/", handler)
mux.HandleFunc("/my-example-url/", FooHandler)
}
在 FooHandler(( 中,我有一些 println((
func FooHandler(w http.ResponseWriter, r *http.Request) {
println("r.URL.Path->",r.URL.Path)
//more business logic
}
// output:
r.URL.Path-> /my-example-url/static/css/normalize.css
r.URL.Path-> /my-example-url/static/libs/xss.js
所以url的初始部分不应该在那里(/my-example-url/部分(
我认为这仅在我尝试使用尾部斜杠为端点提供服务时才会发生,例如:
mux.Handle("/my-example-url/", handler)
我的最终目标是根据我尝试在尾部斜杠后传入 url 的 id 获取一些资源,例如:
http://localhost:3001/my-example-url/bb98610
在 html 文件中,触发静态资源请求的文件,您很可能使用的是相对路径而不是绝对路径,这会导致浏览器将该相对路径附加到地址栏中已有的路径。
例如:
<link href="static/css/normalize.css" rel="stylesheet">
将被浏览器变成/my-example-url/static/css/normalize.css
.
相反,您想使用(注意前导斜杠(:
<link href="/static/css/normalize.css" rel="stylesheet">