dtqjbbr5283 2015-07-31 19:09
浏览 219
已采纳

在Go问题中获取URL参数

I have a URL that looks something like this: http://localhost/templates/verify?key=ijio

My router looks like this:

import (
"github.com/gorilla/mux"
"github.com/justinas/alice"
)

ctx := &model.AppContext{db, cfg} // passes in database and config
verifyUser := controller.Verify(ctx)
mx.Handle("/verify", commonHandlers.ThenFunc(verifyUser)).Methods("GET").Name("verify")

I want to get the key parameter out of the URL, so I use the following code:

func Verify(c *model.AppContext) http.HandlerFunc {
    fn := func(w http.ResponseWriter, r *http.Request) {

    key := r.URL.Query().Get("key") // gets the hash value that was placed in the URL
    log.Println(key) // empty key
    log.Println(r.URL.Query()) // returns map[]
    // code that does something with key and sends back JSON response
   }
}

I used AngularJS to get the JSON data:

app.controller("verifyControl", ['$scope', '$http', function($scope, $http) {
    $scope.message = "";
    $http({
      method: 'GET',
      url: "/verify"
    }).success(function(data) {
         $scope.message = data.msg; // JSON response 
   });

  }]);

However, I end up with an empty key variable when I try to print it out. I recently used nginx to take out my .html extension if that's a possible cause of this problem. How do I fix this?

  • 写回答

1条回答 默认 最新

  • duanchen7703 2015-08-02 02:41
    关注

    The solution to my question involves inspecting the request URL link by

    log.Print(r.URL) // This returns "/verify"
    

    However, that's not exactly what you want. Instead, you want the full URL. You can do the following to get the full URL and extract the parameter from it:

    urlStr := r.Referer()             // gets the full URL as a string
    urlFull, err := url.Parse(urlStr) // returns a *URL object
    if err != nil {
        log.Fatal(err)
        return
    }
    key := urlFull.Query().Get("key") // now we get the key parameter from the URL
    log.Println("Key: " + key) // now you'll get a non empty string
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)