在 Go 问题中获取 URL 参数

我有一个看起来像这样的 URL:http://localhost/templates/verify?key=ijio


我的路由器看起来像这样:


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")

我想从 URL 中获取关键参数,所以我使用以下代码:


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

   }

}

我使用 AngularJS 来获取 JSON 数据:


app.controller("verifyControl", ['$scope', '$http', function($scope, $http) {

    $scope.message = "";

    $http({

      method: 'GET',

      url: "/verify"

    }).success(function(data) {

         $scope.message = data.msg; // JSON response 

   });


  }]);

但是,当我尝试打印它时,我最终得到了一个空的键变量。我最近使用 nginx 删除了我的 .html 扩展名,如果这可能是导致此问题的原因。我该如何解决?


HUX布斯
浏览 410回答 1
1回答

慕哥9229398

我的问题的解决方案涉及通过以下方式检查请求 URL 链接log.Print(r.URL) // This returns "/verify"然而,这并不完全是你想要的。相反,您需要完整的 URL。您可以执行以下操作以获取完整 URL 并从中提取参数:urlStr := r.Referer()             // gets the full URL as a stringurlFull, err := url.Parse(urlStr) // returns a *URL objectif err != nil {    log.Fatal(err)    return}key := urlFull.Query().Get("key") // now we get the key parameter from the URLlog.Println("Key: " + key) // now you'll get a non empty string
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go