如何在使用 slugs 时使用 http.HandleFunc 函数?

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

How to use http.HandleFunc with slugs

问题

我正在进行一个Go项目的工作。当我尝试在http.HandleFunc中使用slug时,我得到一个"404页面未找到错误"。当我去掉slug时,我的路由又可以正常工作。

在main函数中,我有:

  http.HandleFunc("/products/feedback/{slug}", AddFeedbackHandler)

它调用了:

var AddFeedbackHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
  w.Write([]byte("ChecksOut"))
})

当我将路径替换为:

  http.HandleFunc("/products/feedback", AddFeedbackHandler)

它又可以正常工作了。可能是什么原因导致这个问题呢?

英文:

I am working on a Go project. When I try to use slugs with http.HandleFunc I get a "404 page not found error". When I take the slug out my routing works again.

In main I have:

  http.HandleFunc("/products/feedback/{slug}", AddFeedbackHandler)

Which calls:

var AddFeedbackHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
  w.Write([]byte("ChecksOut"))
})

When I replace the path with:

  http.HandleFunc("/products/feedback", AddFeedbackHandler)

It works again. What might be causing this?

答案1

得分: 1

请尝试以下代码:

const feedbackPath = "/products/feedback/"  // 注意末尾的斜杠。

func AddFeedbackHandler(w http.ResponseWriter, r *http.Request) {
  var slug string
  if strings.HasPrefix(r.URL.Path, feedbackPath) {
      slug = r.URL.Path[len(feedbackPath):]
  }
  fmt.Println("the slug is: ", slug)
  w.Write([]byte("ChecksOut"))
}

http.HandleFunc(feedbackPath, AddFeedbackHandler)

路径末尾的斜杠对于子树匹配是必需的。你可以在ServeMux文档中阅读有关末尾斜杠使用的详细信息。

playground示例

英文:

Try the following:

const feedbackPath = "/products/feedback/"  // note trailing slash.

func AddFeedbackHandler(w http.ResponseWriter, r *http.Request) {
  var slug string
  if strings.HasPrefix(r.URL.Path, feedbackPath) {
      slug = r.URL.Path[len(feedbackPath):]
  }
  fmt.Println("the slug is: ", slug)
  w.Write([]byte("ChecksOut"))
}

Add the handler with this code:

http.HandleFunc(feedbackPath, AddFeedbackHandler)

The trailing slash on the path is required for a subtree match. You can read the details on the use of the trailing slash in the ServeMux documentation.

playground example

huangapple
  • 本文由 发表于 2017年2月10日 09:16:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/42149914.html
匿名

发表评论

匿名网友

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

确定