英文:
Add query string url in Go
问题
我需要将HTTP请求发送到https://some-domain.com/getsomething/?id=myID
。我有URL并且需要向其添加查询参数。以下是我的Go代码:
baseUrl := "https://some-domain.com"
relativeUrl := "/getsomething/"
url, _ := url.Parse(baseUrl)
url.Path = path.Join(url.Path, relativeUrl)
// 添加参数到查询字符串
queryString := url.Query()
queryString.Set("id", "1")
// 将查询字符串添加到URL
url.RawQuery = queryString.Encode()
// 打印URL
fmt.Println(url.String())
输出结果是这个URL:https://some-domain.com/getsomething?id=1
而我需要的是这个URL:https://some-domain.com/getsomething/?id=1
你可以看到在?
之前没有/
字符。
你知道如何在不进行手动字符串操作的情况下修复它吗?
https://play.golang.org/p/HsiTzHcvlQ
英文:
I need to send http request to https://some-domain.com/getsomething/?id=myID
I have url and need to add to it a query parameter. Here is my Go code
baseUrl := "https://some-domain.com"
relativeUrl := "/getsomething/"
url, _ := url.Parse(baseUrl)
url.Path = path.Join(url.Path, relativeUrl)
// add parameter to query string
queryString := url.Query()
queryString.Set("id", "1")
// add query to url
url.RawQuery = queryString.Encode()
// print it
fmt.Println(url.String())
In output I see this url: https://some-domain.com/getsomething?id=1
And this one is required: https://some-domain.com/getsomething/?id=1
You can see that there is no /
character before ?
.
Do you know how to fix it without manual string manipulations?
答案1
得分: 10
你可以使用ResolveReference方法。
package main
import (
"fmt"
"log"
"net/url"
)
func main() {
relativeUrl := "/getsomething/"
u, err := url.Parse(relativeUrl)
if err != nil {
log.Fatal(err)
}
queryString := u.Query()
queryString.Set("id", "1")
u.RawQuery = queryString.Encode()
baseUrl := "https://some-domain.com"
base, err := url.Parse(baseUrl)
if err != nil {
log.Fatal(err)
}
fmt.Println(base.ResolveReference(u))
}
英文:
You can use ResolveReference.
package main
import (
"fmt"
"log"
"net/url"
)
func main() {
relativeUrl := "/getsomething/"
u, err := url.Parse(relativeUrl)
if err != nil {
log.Fatal(err)
}
queryString := u.Query()
queryString.Set("id", "1")
u.RawQuery = queryString.Encode()
baseUrl := "https://some-domain.com"
base, err := url.Parse(baseUrl)
if err != nil {
log.Fatal(err)
}
fmt.Println(base.ResolveReference(u))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论