dongmi4809 2016-12-07 03:38
浏览 297
已采纳

net / http:是否可以具有http.HandleFunc自定义参数?

I'm trying to find a way to create special routes to that would allow post request to work with a params ( /url/:param ).

I've tried something like this :

http.HandleFunc("/myroute/:myparam",myfunction)

And i was hopping to be able to get the params as of the http-request in side "myfunction" with req.Form but it keeps on failing on me and i get 404'ed.

I recognize it is something strange to ask as i could pass my params in the body of the function, but for ease of use/display i've been asked to be able to pregenerate a list of static "routes" on some preset so that it can be distributed as different urls + optional params instead of one url for everybody + params..

  • 写回答

1条回答 默认 最新

  • duanbu1421 2016-12-07 03:53
    关注

    It's not possible with the default Mux, but you can use alternative routers like httprouter, Gorilla Mux or chi.

    Here is an example of httprouter usage:

    package main
    
    import (
        "fmt"
        "github.com/julienschmidt/httprouter"
        "net/http"
    )
    
    func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
        fmt.Fprintf(w, "hello, %s!
    ", ps.ByName("name"))
    }
    
    func main() {
        router := httprouter.New()
        router.GET("/hello/:name", Hello)
        http.ListenAndServe(":8080", router)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源