doraemon0769 2018-09-04 16:28
浏览 23
已采纳

无法手动为rest api设置查询参数(使用mux)

I am implementing a Rest api using mux. After validating some parameters, I am trying to fill the missing parameters with some default values which I process later by the method that handles the request, however, I noticed that setting query parameters manually does not have any effect, unless the raw query is directly changed which is a bit hacky:

func ValidateParameters(r *http.Request) (bool) {

     test := r.URL.Query().Get("test")

   // if test is not provided set some default value

    if test == "" {

        r.URL.Query().Set("test", "Test1") //not working
        r.URL.Query().Add("test", "Test2") //not working
        r.URL.RawQuery = r.URL.RawQuery + "&Test=Test3" // the only method working

     }

       // more code

}

The handler is in another file, so I want to be able to do test := r.URL.Query().Get("test") and get the value that I set inside ValidateParameters which is called by the request handler, but this is not working.

any explanation to that ? any way to work around it ?

Thanks.

  • 写回答

1条回答 默认 最新

  • dongtanjian9310 2018-09-04 17:01
    关注

    The problem is that r.URL.Query() parses the url, creates the map of parameters and returns it. This is done with every .Query() call.

    This should work:

    params := r.URL.Query()
    params.Set("key", "value")
    r.URL.RawQuery = params.Encode()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备