Golang:将URL作为GET参数传递 [英] Golang: Passing a URL as a GET parameter

查看:143
本文介绍了Golang:将URL作为GET参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得一个URL作为获取参数



例如:example.com?domain=site.come?a=val&b=val



我使用的问题

  query:= r.URL.Query )
domain:= query.Get(domain)

取得域名它只给出 domain = site.come?a = val

我认为,因为当r.URL.Query()符合 & 它认为它是一个新参数



有人知道我该如何解决这个问题

<

解决方案

您需要对您的查询字符串进行URL编码,像这样

  package main 











查询: = query(url.Values)
query.Add(domain,example.com?foo=bar)

fmt.Println(query.Encode())
}

输出 domain = example.com%3Ffoo%3Dbar



您可以将该字符串设置为 RawQuery http://golang.org/pkg/net/url/#URL =nofollow> url.URL 的值,像你这样的查询,它将具有正确的值。



如果URL正确编码,那么您应该能够运行以下代码与您的网址值并获得正确的结果:

<$ p















$ func main(){
query:= make(url.Values)
query.Add(domain,example.com?foo=bar&abc=123&jkl=qwe)

url:=& url.URL {RawQuery:query.Encode(),Host:domain.com,Scheme:http}
fmt.Println(url.String() )

abc:= url.Query()。Get(domain)
fmt.Println(abc)



$ b $ p
$ b



$ b pre> http://domain.com?domain=example.com%3Ffoo%3Dbar%26abc%3D123%26jkl%3Dqwe
$ b

(编码参数称为domain的完整URI)

  example.com?foo=bar&abc=123&jkl=qwe 

(解码值的参数)

I want to get an URL as a get aparameter

ex: example.com?domain=site.come?a=val&b=val

the problem when i use

query := r.URL.Query()
domain := query.Get("domain") 

to get the domain name it give just domain=site.come?a=val

I think because when the r.URL.Query() meet & it consider it as a new parameter

does anyone know how can I solve this problem

Thank you in advance.

解决方案

You need to URL-Encode your query string, like this:

package main

import (
    "fmt"
    "net/url"
)

func main() {
    query := make(url.Values)
    query.Add("domain", "example.com?foo=bar")

    fmt.Println(query.Encode())
}

Which outputs domain=example.com%3Ffoo%3Dbar.

You can set that string as a RawQuery of an url.URL value and if you then access the query like you did, it will have the correct value.

If the URL is correctly encoded then you should be able to run the following code with your URL value and get the correct result:

package main

import (
    "fmt"
    "net/url"
)

func main() {
    query := make(url.Values)
    query.Add("domain", "example.com?foo=bar&abc=123&jkl=qwe")

    url := &url.URL{RawQuery: query.Encode(), Host: "domain.com", Scheme: "http"}
    fmt.Println(url.String())

    abc := url.Query().Get("domain")
    fmt.Println(abc)
}

This prints:

http://domain.com?domain=example.com%3Ffoo%3Dbar%26abc%3D123%26jkl%3Dqwe

(the complete URI with the encoded parameter called "domain")

example.com?foo=bar&abc=123&jkl=qwe

(the decoded value of said parameter)

这篇关于Golang:将URL作为GET参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆