为了账号安全,请及时绑定邮箱和手机立即绑定

在 Go 问题中获取 URL 参数

在 Go 问题中获取 URL 参数

Go
HUX布斯 2021-10-25 18:34:13
我有一个看起来像这样的 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 configverifyUser := 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 扩展名,如果这可能是导致此问题的原因。我该如何解决?
查看完整描述

1 回答

?
慕哥9229398

TA贡献1877条经验 获得超6个赞

我的问题的解决方案涉及通过以下方式检查请求 URL 链接


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

然而,这并不完全是你想要的。相反,您需要完整的 URL。您可以执行以下操作以获取完整 URL 并从中提取参数:


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


查看完整回答
反对 回复 2021-10-25
  • 1 回答
  • 0 关注
  • 409 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信