如何限制用golang编写的web服务器允许一个特定的地址而不是一个模式? [英] How to restrict web server written in golang to allow a particular address instead of a pattern?
问题描述
http.HandleFunc(/,serveRest)// serveRest是处理请求的方法
http.ListenAndServe(localhost:4000,nil)
它会接受所有请求开始与/
。我如何限制它只为>localhost:4000
,而不是像localhost:4000 / *
?
你们可以为我推荐一个好的Go教程吗?
注册处理程序的URL模式记录在 http.ServeMux
类型:
$ b
模式名称固定的根路径,如/ favicon.ico,或根源子树,如/ images /(注意尾部斜线)。较长的模式优先于较短的模式,因此如果有处理程序注册了/ images /和/ images / thumbnails /,后一个处理程序将调用路径以/ images / thumbnails /开头,前者将收到/ images /子树中任何其他路径的请求。
请注意,由于以斜线结尾的模式命名了根子树,匹配所有未被其他注册模式匹配的路径,而不仅仅是具有Path ==/\".
所以不幸的是没有它只匹配根(/
)。
但是你可以在你的处理程序中轻松地检查它,如果请求路径不是根目录,你可以做任何你想做的事:
func serveRest(w http.ResponseWriter,r * http .Request){
if r.URL.Path!=/{
w.Write([] byte(Not root!))
return
}
w.Write([] byte(这是root!))
}
如果您想返回 HTTP 404找不到
b
$ b
func serveRest(w http.ResponseWriter,r * http.Request){
if r.URL.Path!=/{
http.NotFound(w,r)
return
}
w.Write([]字节(Hi!))
}
Go教程: https://tour.golang.org/
另外检查在 上转到 标签信息,它包含 Go Tutorials 。
When I use
http.HandleFunc("/", serveRest) //serveRest is the method to handle request
http.ListenAndServe("localhost:4000", nil)
It will accept all request starting with "/"
. How do I restrict it to serve only "localhost:4000"
instead of every address like "localhost:4000/*"
?
And can you guys suggest me a good tutorial for Go?
The URL pattern to which you register your handlers is documented in the http.ServeMux
type:
Patterns name fixed, rooted paths, like "/favicon.ico", or rooted subtrees, like "/images/" (note the trailing slash). Longer patterns take precedence over shorter ones, so that if there are handlers registered for both "/images/" and "/images/thumbnails/", the latter handler will be called for paths beginning "/images/thumbnails/" and the former will receive requests for any other paths in the "/images/" subtree.
Note that since a pattern ending in a slash names a rooted subtree, the pattern "/" matches all paths not matched by other registered patterns, not just the URL with Path == "/".
So unfortunately there is no pattern which matches only the root ("/"
).
But you can easily check this in your handler, and do whatever you want to if the request path is not the 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!"))
}
If you want to return HTTP 404 Not found
error for non-roots:
func serveRest(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
w.Write([]byte("Hi!"))
}
And Go tutorial: https://tour.golang.org/
Also check out the Go tag info here on SO, it has a section Go Tutorials.
这篇关于如何限制用golang编写的web服务器允许一个特定的地址而不是一个模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!