Add query string url in Go

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

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?

https://play.golang.org/p/HsiTzHcvlQ

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

https://play.golang.org/p/BIU29R_XBM

huangapple
  • 本文由 发表于 2017年9月13日 18:43:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/46195423.html
匿名

发表评论

匿名网友

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

确定