duanbi1888 2015-07-12 18:26
浏览 131
已采纳

mux.Vars不起作用

I'm running on HTTPS (port 10443) and use subroutes:

mainRoute := mux.NewRouter()
mainRoute.StrictSlash(true)
mainRoute.Handle("/", http.RedirectHandler("/static/", 302))
mainRoute.PathPrefix("/static/").Handler(http.StripPrefix("/static", *fh))

// Bind API Routes
apiRoute := mainRoute.PathPrefix("/api").Subrouter()

apiProductRoute := apiRoute.PathPrefix("/products").Subrouter()
apiProductRoute.Handle("/", handler(listProducts)).Methods("GET")

And the functions:

func listProducts(w http.ResponseWriter, r *http.Request) (interface{}, *handleHTTPError) {
    vars := mux.Vars(r)

    productType, ok := vars["id"]
    log.Println(productType)
    log.Println(ok)
}

ok is false and I have no idea why. I'm doing a simple ?type=model after my URL..

  • 写回答

2条回答 默认 最新

  • donglijuan8227 2015-07-12 21:10
    关注

    When you enter a URL like somedomain.com/products?type=model you're specifying a query string, not a variable.

    Query strings in Go are accessed via r.URL.Query - e.g.

    vals := r.URL.Query() // Returns a url.Values, which is a map[string][]string
    productTypes, ok := vals["type"] // Note type, not ID. ID wasn't specified anywhere.
    var pt string
    if ok {
        if len(productTypes) >= 1 {
            pt = productTypes[0] // The first `?type=model`
        }
    }
    

    As you can see, this can be a little clunky as it has to account for the map value being empty and for the possibility of a URL like somedomain.com/products?type=model&this=that&here=there&type=cat where a key can be specified more than once.

    As per the gorilla/mux docs you can use route variables:

       // List all products, or the latest
       apiProductRoute.Handle("/", handler(listProducts)).Methods("GET")
       // List a specific product
       apiProductRoute.Handle("/{id}/", handler(showProduct)).Methods("GET")
    

    This is where you would use mux.Vars:

    vars := mux.Vars(request)
    id := vars["id"]
    

    Hope that helps clarify. I'd recommend the variables approach unless you specifically need to use query strings.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么