英文:
httprouter.GET not working
问题
我有一个使用GET方法提交数据的HTML表单。
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Web Search</title>
</head>
<body>
<form action="/search" method="get">
<label for="tags">Enter your tags(Comma separated)</label>
<br>
<input type="text" name="tags">
<input type="submit">
</form>
</body>
</html>
这是我的Go代码:
package main
import (
"net/http"
"log"
"html/template"
"fmt"
"github.com/julienschmidt/httprouter"
)
func main() {
router := httprouter.New()
router.GET("/", Search)
router.GET("/search?key=:tags", GrabQuestions)
log.Fatal(http.ListenAndServe(":8080", router))
}
func Search(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
t, err := template.ParseFiles("E:/work/src/github.com/krashcan/sos/template/index.html")
if err != nil {
log.Println(err)
}
t.Execute(w, nil)
}
func GrabQuestions(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "Tags were %s", ps.ByName("tags"))
}
我期望这段代码在点击提交按钮时简单地打印出标签(func GrabQuestions 最终将提供不同的任务,因此我不是在寻找打印搜索关键字的替代方法),但是当我点击提交按钮时,它显示一个"404页面未找到"的错误。我认为我犯了一些愚蠢的错误,但我就是找不到。我漏掉了什么?
英文:
I have a html form which is submitting data using a get-method.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Web Search</title>
</head>
<body>
<form action="/search" method="get">
<label for="tags">Enter your tags(Comma separated)</label>
<br>
<input type="text" name="tags">
<input type="submit">
</form>
</body>
</html>
and this is my go code
package main
import (
"net/http"
"log"
"html/template"
"fmt"
"github.com/julienschmidt/httprouter"
)
func main() {
router := httprouter.New()
router.GET("/",Search)
router.GET("/search?key=:tags",GrabQuestions)
log.Fatal(http.ListenAndServe(":8080",router))
}
func Search(w http.ResponseWriter,r *http.Request,_ httprouter.Params){
t,err := template.ParseFiles("E:/work/src/github.com/krashcan/sos/template/index.html")
if err!= nil{
log.Println(err)
}
t.Execute(w,nil)
}
func GrabQuestions(w http.ResponseWriter,r *http.Request,ps httprouter.Params){
fmt.Fprintf(w,"Tags were %s", ps.ByName("tags"))
}
I expected this code to simply print the tags when the submit button was pressed(func GrabQuestions will eventually serve a different task so an alternative way to print the search keys is not what I am looking for), but when I click the submit button, it gives a 404 page not found
error. I think there is some silly mistake on my part but I just dont see it. What am I missing?
答案1
得分: 0
正如Frank在他的评论中指出的那样,httprouter不支持通过“查询参数”进行路由,所以你应该将搜索路由的定义更改为以下形式:
router.GET("/search", GrabQuestions)
英文:
As Frank pointed out in his comment, httprouter doesn't support routing by "query parameters" so you should change your search route definition to something like this:
router.GET("/search", GrabQuestions)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论