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

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

Go: Represent path without query string

问题

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

例如:

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

以下代码无效:

Go:

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

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:

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

答案1

得分: 7

func main() {
    req, err := http.NewRequest("GET", "http://www.example.com/user?id=1", nil)
    if err != nil {
        log.Fatal(err)
    }

    // 获取主机名
    fmt.Printf("%v\n", req.Host) // 输出: www.example.com

    // 获取路径(不包含查询字符串)
    fmt.Printf("%v\n", req.URL.Path) // 输出: /user

    // 根据键获取查询字符串的值
    fmt.Printf("%v\n", req.URL.Query().Get("id")) // 输出: 1

    // 原始查询字符串
    fmt.Printf("%v\n", req.URL.RawQuery) // 输出: id=1
}

Go [play](http://play.golang.org/p/oqSxCV89vP)
英文:
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
}

Go play

答案2

得分: 0

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

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

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

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

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

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

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

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:

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

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

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

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

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

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:

确定