dougengqiu8031 2017-01-06 14:23 采纳率: 100%
浏览 100
已采纳

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 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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大