英文:
Read a requested URL path without a predefined route, in Golang
问题
我正在创建一个Go Web应用程序,在其中我需要读取一个URL,例如example.com/person/(任意名称)。
如何读取并打印任意名称?
英文:
I am creating a Go web app in which I need to read a URL like example.com/person/(any_name)
How can I read and print any_name?
答案1
得分: 5
你应该考虑使用gorilla/mux包来完成你想要做的事情。
从该包的GitHub页面上摘录如下:https://github.com/gorilla/mux
r := mux.NewRouter()
r.HandleFunc("/products/{key}", ProductHandler)
r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
英文:
You should look into using gorilla/mux package for what you are trying to do.
An excerpt from the package github shows https://github.com/gorilla/mux
r := mux.NewRouter()
r.HandleFunc("/products/{key}", ProductHandler)
r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
答案2
得分: 3
如果你查看这个页面 https://golang.org/doc/articles/wiki/,里面有一些我认为你想要的示例。
你想要一个名为person的处理程序,然后提取(任意名称)并根据每个人进行相应的处理。其中一个示例展示了如何使用title来实现相同的原理。
func viewHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[len("/view/"):]
p, _ := loadPage(title)
t, _ := template.ParseFiles("view.html")
t.Execute(w, p)
}
不同的是,你的路径是/person/,而title在你的情况下就是(任意名称)。
r.URL.Path[len("/view/"):]
将从 r.URL.Path
中取出从第 len("/view/")
个字节开始的所有内容。
英文:
If you take a look at this page <https://golang.org/doc/articles/wiki/> there are examples of what I think you are after.
You want a handler with name person and then extract (any_name) and handle it accordingly to each person. One of the examples shows how to do it with title which is the same principle.
func viewHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[len("/view/"):]
p, _ := loadPage(title)
t, _ := template.ParseFiles("view.html")
t.Execute(w, p)
}
Instead of /view/ you got /person/ and title is what (any_name) is in your case.
r.URL.Path[len("/view/"):]
will take everything from r.URL.Path
but start len("/view/")
bytes into the slice.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论