如何代表没有查询字符串的路径?转:代表没有查询字符串的路径
例如:
www.example.com/user
而不是www.example.com/user?id=1
下面的代码没有工作:
转到:
if r.URL.Path[4:] != "" {
//do something
}
如何代表没有查询字符串的路径?转:代表没有查询字符串的路径
例如:
www.example.com/user
而不是www.example.com/user?id=1
下面的代码没有工作:
转到:
if r.URL.Path[4:] != "" {
//do something
}
要向网址添加参数,您需要使用Values()
。
也就是说,没有任何参数的URL可以具有它的 '价值' 的长度设置为0:
if len(r.URL.Query()) == 0 {
}
这应该是相同the comments建议通过Dewy Broto的r.URL.RawQuery
:
if r.URL.RawQuery == "" {
}
或者您可以检查Values()
地图中的密钥“id
”是否存在。
if r.URL.Query().Get("id") == "" {
//do something here
}
func main() {
req, err := http.NewRequest("GET", "http://www.example.com/user?id=1", nil)
if err != nil {
log.Fatal(err)
}
// get host
fmt.Printf("%v\n", req.Host) // Output: www.example.com
// path without query string
fmt.Printf("%v\n", req.URL.Path) // Output: /user
// get query string value by key
fmt.Printf("%v\n", req.URL.Query().Get("id")) // Output: 1
// raw query string
fmt.Printf("%v\n", req.URL.RawQuery) // Output: id=1
}
转到play
@DewyBroto完成 – jmaloney 2014-10-06 16:05:07
我用了一个简单的r.URL.Query(),它给了我一个地图。但是,如果r.URL.Query!= nil不起作用。 – user3918985 2014-10-04 04:42:06
@ user3918985您是否尝试过'r.URL.Values()',看看它是否更好? – VonC 2014-10-04 05:18:57
yup,我得到这个错误:r.URL.Values未定义(类型* url.URL没有字段或方法值) – user3918985 2014-10-04 05:30:28