如何在Golang中建立URL/查询 [英] How to build a URL / Query in Golang
问题描述
背景-
我需要根据用于表单调用的表单中的用户输入来构建URL/查询.
I need to build a URL / query based on user input from a form that will be used to make an API call.
问题-
构建URL时,无法正确转义参数.例如,查询"bad santa"最终在它们之间有一个空格,而不是"+".
When building the URL, the params are not properly escaped. For example, the query "bad santa" ends up with a space between it instead of "+".
电流输出-
例如 https://api.example.org/3/search/movie?query=不好santa& api_key = #######
e.g. https://api.example.org/3/search/movie?query=bad santa&api_key=#######
预期输出-
例如 https://api.example.org/3/search/movie?query=bad+santa&api_key=########
代码示例-
根URL-
var SearchUrl = "https://www.example.org/3/search/movie?query="
获取从用户输入中获取的参数-
Get params taken from user input -
var MovieSearch []string = r.Form["GetSearchKey"]
API密钥-
var apiKey = "&api_key=######"
我正在使用 ArrayToString()
来解析表单输入数据
I am using the ArrayToString()
to parse the form input data
func ArrayToString(array []string) string{
str := strings.Join(array, "+")
return str
}
然后构建URL-
var SearchUrl = "https://api.example.org/3/search/movie?query="
var MovieSearch []string = r.Form["GetSearchKey"]
var apiKey = "&api_key=########"
UrlBuild := []string {SearchUrl, ArrayToString(MovieSearch), apiKey}
OUTPUT_STRING := ArrayToString(UrlBuild)
问题-
如何使用正确输入的用户输入GET参数构建URL?
How to build a URL with user input GET params that are escaped properly?
推荐答案
通常,应该使用url包的值.
Normally, one should use url package's Values.
这是一个示例,它满足了我的要求,在播放中既是简单的main,又是http.HandlerFunc形式:
Here's an example, that does what I think you want, on play Both a simple main, and in http.HandlerFunc form:
package main
import "fmt"
import "net/url"
import "net/http"
func main() {
baseURL := "https://www.example.org/3/search/movie"
v := url.Values{}
v.Set("query", "this is a value")
perform := baseURL + "?" + v.Encode()
fmt.Println("Perform:", perform)
}
func formHandler(w http.ResponseWriter, r *http.Request) {
baseURL := "https://www.example.org/3/search/movie"
v := url.Values{}
v.Set("query", r.Form.Get("GetSearchKey")) // take GetSearchKey from submitted form
v.Set("api_ley", "YOURKEY") // whatever your api key is
perform := baseURL + "?" + v.Encode() // put it all together
fmt.Println("Perform:", perform) // do something with it
}
输出:执行:https://www.example.org/3/search/movie?query=this+is+a+value
请注意如何为您正确地将值放入查询字符串中.
Notice how the values are put in to query string, properly escaped, for you.
这篇关于如何在Golang中建立URL/查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!