Go:表示不带查询字符串的路径

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

Go: Represent path without query string

问题

如何表示没有查询字符串的路径?

例如:

  • www.example.com/user 而不是
  • www.example.com/user?id=1

以下代码无效:

Go:

  1. if r.URL.Path[4:] != "" {
  2. //do something
  3. }
英文:

How do I represent a path without query string?

Eg.:

  • www.example.com/user instead of
  • www.example.com/user?id=1

The following code didn't work:

Go:

  1. if r.URL.Path[4:] != "" {
  2. //do something
  3. }

答案1

得分: 7

  1. func main() {
  2. req, err := http.NewRequest("GET", "http://www.example.com/user?id=1", nil)
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. // 获取主机名
  7. fmt.Printf("%v\n", req.Host) // 输出: www.example.com
  8. // 获取路径(不包含查询字符串)
  9. fmt.Printf("%v\n", req.URL.Path) // 输出: /user
  10. // 根据键获取查询字符串的值
  11. fmt.Printf("%v\n", req.URL.Query().Get("id")) // 输出: 1
  12. // 原始查询字符串
  13. fmt.Printf("%v\n", req.URL.RawQuery) // 输出: id=1
  14. }
  15. Go [play](http://play.golang.org/p/oqSxCV89vP)
英文:
  1. func main() {
  2. req, err := http.NewRequest("GET", "http://www.example.com/user?id=1", nil)
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. // get host
  7. fmt.Printf("%v\n", req.Host) // Output: www.example.com
  8. // path without query string
  9. fmt.Printf("%v\n", req.URL.Path) // Output: /user
  10. // get query string value by key
  11. fmt.Printf("%v\n", req.URL.Query().Get("id")) // Output: 1
  12. // raw query string
  13. fmt.Printf("%v\n", req.URL.RawQuery) // Output: id=1
  14. }

Go play

答案2

得分: 0

要向URL添加参数,您可以使用Values()

这意味着没有任何参数的URL的'Values'长度将设置为0:

  1. if len(r.URL.Query()) == 0 {
  2. }

这与Dewy Broto评论中建议的r.URL.RawQuery相同:

  1. if r.URL.RawQuery == "" {
  2. }

或者您可以检查Values()映射中是否存在键'id'。

  1. if r.URL.Query().Get("id") == "" {
  2. //在这里执行某些操作
  3. }
英文:

To add parameters to an url, you would use Values().

That means, an URL without any parameters would have its 'Values' length set to 0:

  1. if len(r.URL.Query()) == 0 {
  2. }

That should be the same as the r.URL.RawQuery suggested by Dewy Broto in the comments:

  1. if r.URL.RawQuery == "" {
  2. }

Or you can check for the presence if the key 'id' in the Values() map.

  1. if r.URL.Query().Get("id") == "" {
  2. //do something here
  3. }

huangapple
  • 本文由 发表于 2014年10月4日 12:11:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/26189523.html
匿名

发表评论

匿名网友

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

确定