在Golang中,读取一个没有预定义路由的请求URL路径。

huangapple go评论90阅读模式
英文:

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(&quot;/view/&quot;):]
    p, _ := loadPage(title)
    t, _ := template.ParseFiles(&quot;view.html&quot;)
    t.Execute(w, p)
}

Instead of /view/ you got /person/ and title is what (any_name) is in your case.

r.URL.Path[len(&quot;/view/&quot;):] will take everything from r.URL.Path but start len(&quot;/view/&quot;) bytes into the slice.

huangapple
  • 本文由 发表于 2017年7月30日 15:53:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/45397625.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定