dougengqiu8031
dougengqiu8031
采纳率100%
2017-01-06 14:23 阅读 95
已采纳

httprouter.GET不起作用

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条回答 默认 最新

  • 已采纳
    duanche2007 duanche2007 2017-01-06 14:55

    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)
    
    点赞 评论 复制链接分享

相关推荐