Golang:将URL作为GET参数传递

huangapple go评论79阅读模式
英文:

Golang: Passing a URL as a GET parameter

问题

我想要将一个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() 遇到 & 时,它将其视为一个新的参数。

有人知道如何解决这个问题吗?

提前谢谢。

英文:

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.

答案1

得分: 3

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

package main

import (
	"fmt"
	"net/url"
)

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

	fmt.Println(query.Encode())
}

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

你可以将该字符串设置为 url.URL 值的 RawQuery,然后像你那样访问查询,它将具有正确的值。

如果URL已经正确编码,那么你应该能够使用你的URL值运行以下代码,并获得正确的结果:

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

这将输出:

http://domain.com?domain=example.com%3Ffoo%3Dbar%26abc%3D123%26jkl%3Dqwe
(带有编码参数“domain”的完整URI)

example.com?foo=bar&abc=123&jkl=qwe
(该参数的解码值)
英文:

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)

huangapple
  • 本文由 发表于 2015年6月5日 17:04:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/30662512.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定