英文:
How to create a route with optional url var using gorilla mux?
问题
我想在路由中添加一个可选的URL变量。我似乎找不到使用mux包的方法。这是我的当前路由:
func main() {
r := mux.NewRouter()
r.HandleFunc("/view/{id:[0-9]+}", MakeHandler(ViewHandler))
http.Handle("/", r)
http.ListenAndServe(":8080", nil)
}
当URL为localhost:8080/view/1
时,它可以正常工作。我希望即使没有id
,它也能接受URL,这样如果我输入localhost:8080/view
,它仍然可以工作。你有什么想法?
英文:
I want to have an optional URL variable in route. I can't seem to find a way using mux package. Here's my current route:
func main() {
r := mux.NewRouter()
r.HandleFunc("/view/{id:[0-9]+}", MakeHandler(ViewHandler))
http.Handle("/", r)
http.ListenAndServe(":8080", nil)
}
It works when the url is localhost:8080/view/1
. I want it to accept even if there's no id
so that if I enter localhost:8080/view
it'll still work. Thoughts?
答案1
得分: 9
请问您需要将这段代码翻译成中文吗?
英文:
Register the handler a second time with the path you want:
r.HandleFunc("/view", MakeHandler(ViewHandler))
Just make sure when you are getting your vars that you check for this case:
vars := mux.Vars(r)
id, ok := vars["id"]
if !ok {
// directory listing
return
}
// specific view
答案2
得分: 5
你可以为根路径/view
定义一个新的HandleFunc
:
r.HandleFunc("/view", MakeHandler(RootHandler))
然后,RootHandler
函数可以根据你的需求处理该路径。
英文:
You could define a new HandleFunc
for the root /view
path:
r.HandleFunc("/view", MakeHandler(RootHandler))
And have the RootHandler
function do whatever you require for that path.
答案3
得分: 0
你可以使用?
字符来表示id:[0-9]+
模式是可选的,并在ViewHandler
函数中处理是否传递了id
。
main
:
func main() {
r := mux.NewRouter()
r.HandleFunc("/view/{id:[0-9]+?}", MakeHandler(ViewHandler))
http.Handle("/", r)
http.ListenAndServe(":8080", nil)
}
ViewHandler
:
func ViewHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
if id == "" {
fmt.Println("没有提供id")
} else {
fmt.Println("提供了id")
}
}
英文:
You can use the ?
character to indicate that the id:[0-9]+
pattern is optional, and handle whenever there is an id
is passed or not in your ViewHandler
function.
main
:
func main() {
r := mux.NewRouter()
r.HandleFunc("/view/{id:[0-9]+?}", MakeHandler(ViewHandler))
http.Handle("/", r)
http.ListenAndServe(":8080", nil)
}
ViewHandler
:
func ViewHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
if id == "" {
fmt.Println("there is no id")
} else {
fmt.Println("there is an id")
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论