Sha*_*esh 2 http go url-pattern server
我用的时候
http.HandleFunc("/", serveRest) //serveRest is the method to handle request
http.ListenAndServe("localhost:4000", nil)
Run Code Online (Sandbox Code Playgroud)
它将接受所有请求"/".如何限制它仅用于"localhost:4000"代替每个地址"localhost:4000/*"?
你们可以给我一个很好的Go教程吗?
注册处理程序的URL模式记录在http.ServeMux类型中:
模式名称固定,带根的路径,如"/favicon.ico",或带根的子树,如"/ images /"(请注意尾部斜杠).较长的模式优先于较短的模式,因此如果有"/ images /"和"/ images/thumbnails /"注册的处理程序,后面的处理程序将被调用以开始"/ images/thumbnails /"的路径和前者将收到"/ images /"子树中任何其他路径的请求.
请注意,由于以斜杠结尾的模式命名为有根子树,因此模式"/"匹配所有未与其他已注册模式匹配的路径,而不仅仅是具有Path =="/"的URL.
所以不幸的是,没有模式只匹配root("/").
但是你可以在你的处理程序中轻松检查这个,如果请求路径不是root,你可以做任何你想做的事情:
func serveRest(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
w.Write([]byte("Not root!"))
return
}
w.Write([]byte("Hi, this is the root!"))
}
Run Code Online (Sandbox Code Playgroud)
如果要HTTP 404 Not found为非根返回错误:
func serveRest(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
w.Write([]byte("Hi!"))
}
Run Code Online (Sandbox Code Playgroud)
和Go教程:https://tour.golang.org/
另外Go在SO上查看标签信息,它有一个Go Tutorials部分.