gpt4 book ai didi

http - 如何限制用 golang 编写的 Web 服务器允许特定地址而不是模式?

转载 作者:IT王子 更新时间:2023-10-29 01:20:03 25 4
gpt4 key购买 nike

当我使用

http.HandleFunc("/", serveRest)  //serveRest is the method to handle request
http.ListenAndServe("localhost:4000", nil)

它将接受所有以"/"开头的请求。我如何限制它只提供 "localhost:4000" 而不是像 "localhost:4000/*" 这样的每个地址?

你们能给我推荐一个好的 Go 教程吗?

最佳答案

您向其注册处理程序的 URL 模式记录在 http.ServeMux 中。输入:

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 == "/".

很遗憾,没有只匹配根 ("/") 的模式。

但是你可以很容易地在你的处理程序中检查它,如果请求路径不是根路径,你可以做任何你想做的事情:

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!"))
}

如果您想为非根用户返回 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!"))
}

Go 教程:https://tour.golang.org/

另请查看 Go 在此处标记信息,它有一个部分 Go Tutorials

关于http - 如何限制用 golang 编写的 Web 服务器允许特定地址而不是模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31877296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com