如何使 fmt.Sprint 在 URL 的参数中工作?

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

How to make fmt.Sprint spring work for parameters in a URL?

问题

我有一个反向代理,用于返回来自第三方API的响应体。这个第三方API使用分页,所以我的反向代理路径需要包含页码参数。

我在使用fmt.Sprint将参数从反向代理URL传递给第三方API请求时遇到了问题。

func (s *Server) getReverseProxy(w http.ResponseWriter, r *http.Request) {
	keys, ok := r.URL.Query()["page"]

	if !ok || len(keys[0]) < 1 {
		log.Println("Url Param 'page' is missing")
		return
	}

	// Query()["key"] will return an array of items,
	// we only want the single item.
	key := keys[0]

	log.Println("Url Param 'page' is: " + string(key))

	// create http client to make GET request to reverse-proxy
	client := &http.Client{}

	// create 3rd party request

    // creating this request is causing me the issue due to the page parameter 
	req, err := http.NewRequest("GET", fmt.Sprint("https://url.com/path?&page%5Bsize%5D=100&page%5Bnumber%5D=%s\n", key), nil)

    // more stuff down here but omitted for brevity.
}

观察http.NewRequest的第三方API请求,%s\n部分是用于传递key作为page parameter的地方。

我应该如何正确地将这个变量传递给URL?在Python中,我想要使用的是f-string。不确定我是否正确地在Go中使用了它。

编辑:
使用url.Values()的新实现:

func (s *Server) getReverseProxy(w http.ResponseWriter, r *http.Request) {
	keys, ok := r.URL.Query()["page"]

	if !ok || len(keys[0]) < 1 {
		log.Println("Url Param 'page' is missing")
		return
	}

	// Query()["key"] will return an array of items,
	// we only want the single item.
	key := keys[0]

	log.Println("Url Param 'page' is: " + string(key))
	params := url.Values{
		"page[size]":        []string{"100"},
		"page[" + key + "]": []string{"1"},
	}
	u := &url.URL{
		Scheme:   "https",
		Host:     "url.com",
		Path:     "/path",
		RawQuery: params.Encode(),
	}

	// create http client to make GET request
	client := &http.Client{}

	// create a variable for the JSON model expected from Terraform Cloud API
	var data models.TerraformResponse
	req, err := http.NewRequest("GET", u.String(), nil)
}
英文:

I have a reverse-proxy that returns body responses from a 3rd party API. This 3rd party API uses pagination, so my reverse-proxy path requires parameters for page number.

I'm having trouble using fmt.Sprint to pass the parameter from the reverse-proxy URL to 3rd Party API request.

func (s *Server) getReverseProxy(w http.ResponseWriter, r *http.Request) {
	keys, ok := r.URL.Query()[&quot;page&quot;]

	if !ok || len(keys[0]) &lt; 1 {
		log.Println(&quot;Url Param &#39;page&#39; is missing&quot;)
		return
	}

	// Query()[&quot;key&quot;] will return an array of items,
	// we only want the single item.
	key := keys[0]

	log.Println(&quot;Url Param &#39;page&#39; is: &quot; + string(key))

	// create http client to make GET request to reverse-proxy
	client := &amp;http.Client{}

	// create 3rd party request

    // creating this request is causing me the issue due to the page parameter 
	req, err := http.NewRequest(&quot;GET&quot;, fmt.Sprint(&quot;https://url.com/path?&amp;page%5Bsize%5D=100&amp;page%5Bnumber%5D=%s\n&quot;, key), nil)

    // more stuff down here but omitted for brevity.
}

Looking at the http.NewRequest 3rd party api request, the %s\n part would be where they key is passed for the page parameter.

How can I correctly pass this variable to the url? In python what I'm looking to use is an f-string. Not sure im doing that correctly for Go.

EDIT:
New implementation using url.Vaues()

func (s *Server) getReverseProxy(w http.ResponseWriter, r *http.Request) {
	keys, ok := r.URL.Query()[&quot;page&quot;]

	if !ok || len(keys[0]) &lt; 1 {
		log.Println(&quot;Url Param &#39;page&#39; is missing&quot;)
		return
	}

	// Query()[&quot;key&quot;] will return an array of items,
	// we only want the single item.
	key := keys[0]

	log.Println(&quot;Url Param &#39;page&#39; is: &quot; + string(key))
	params := url.Values{
		&quot;page[size]&quot;:        []string{&quot;100&quot;},
		&quot;page[&quot; + key + &quot;]&quot;: []string{&quot;1&quot;},
	}
	u := &amp;url.URL{
		Scheme:   &quot;https&quot;,
		Host:     &quot;url.com&quot;,
		Path:     &quot;/path&quot;,
		RawQuery: params.Encode(),
	}

	// create http client to make GET request
	client := &amp;http.Client{}

	// create a variable for the JSON model expected from Terraform Cloud API
	var data models.TerraformResponse
	req, err := http.NewRequest(&quot;GET&quot;, u.String(), nil)
}

答案1

得分: 4

你应该使用net/url包来构建URL和查询。这样做的好处是更安全。

params := url.Values{
    "page[size]":        []string{"100"},
    "page[" + key + "]": []string{"1"},
}
u := &url.URL{
    Scheme:   "https",
    Host:     "url.com",
    Path:     "/path",
    RawQuery: params.Encode(),
}
req, err := http.NewRequest("GET", u.String(), nil)

尝试使用fmt.Sprintf()构建URL可能更容易出错。

如果你想使用fmt.Sprintf构建URL,你需要转义格式字符串中的所有%,并转义参数中的特殊字符。

fmt.Sprint("https://url.com/path?&page%%5Bsize%%5D=100&page%%5B%s%%5D=1",
    url.QueryEscape(key))

url.QueryEscape()函数会对字符串中的字符进行转义,以便安全地放置在URL查询中。如果你使用url.Valuesurl.URL构建URL,这个函数就不是必需的。

英文:

You should probably be constructing the URL and query using the net/url package. This has the advantage that it is much safer.

params := url.Values{
    &quot;page[size]&quot;:        []string{&quot;100&quot;},
    &quot;page[&quot; + key + &quot;]&quot;: []string{&quot;1&quot;},
}
u := &amp;url.URL{
    Scheme:   &quot;https&quot;,
    Host:     &quot;url.com&quot;,
    Path:     &quot;/path&quot;,
    RawQuery: params.Encode(),
}
req, err := http.NewRequest(&quot;GET&quot;, u.String(), nil)

Trying to use fmt.Sprintf() to construct URLs is a bit more likely to backfire.

If you want to construct a URL with fmt.Sprintf, you’ll need to escape all the % in the format string, and escape special characters in the arguments.

fmt.Sprint(&quot;https://url.com/path?&amp;page%%5Bsize%%5D=100&amp;page%%5B%s%%5D=1&quot;,
    url.QueryEscape(key))

The url.QueryEscape() function escapes the characters in a string so it can be safely placed in a URL query. It’s not necessary if you construct the URL with url.Values and url.URL.

huangapple
  • 本文由 发表于 2022年2月19日 09:45:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/71181689.html
匿名

发表评论

匿名网友

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

确定