2017-02-10 11 views
-1

嗨,我正在开发一个golang项目。当我尝试使用http.HandleFunc使用slug时,出现“404页未找到错误”。当我拿出弹子时,我的路由再次工作。Golang http.HandleFunc不能与slu working一起工作

在主,我有:

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) 

它工作一次。什么可能导致这种情况?请原谅我,如果这是一个基本的问题,我是golang新手,仍然试图抓住它。谢谢!

+1

AWAIK,当前Golang的HTTP库不支持captureing'{}塞在'的路径,也许你应该使用类似https://github.com/gorilla/mux – ymonad

+1

注意,文档HandleFunc不声称支持slu。。 Go文档非常好,您通常可以假定不存在功能而不是文档。 – Adrian

回答

1

尝试以下操作:

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

添加处理程序使用此代码:

http.HandleFunc(feedbackPath, AddFeedbackHandler) 

的道路上尾随斜线需要一个子树匹配。您可以阅读关于使用ServeMux documentation中的斜线的详细信息。

playground example