3

golang 如何解析url中的多个参数

 2 years ago
source link: https://studygolang.com/articles/28129?fr=sidebar
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

golang 如何解析url中的多个参数

yufeifly · 2020-04-21 17:36:02 · 3126 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    
这是一个创建于 2020-04-21 17:36:02 的文章,其中的信息可能已经有所发展或是发生改变。

以下面的url为例,这个例子实际上是《go语言圣经》中7.7章节http.handler的一个例子。我们需要更新袜子socks的价钱为16,鞋子shoes的价格为100。我们把它们写到同一个url中。对于这种一个url有多个参数的情况该如何处理呢?

http://localhost:8000/update?item=socks&price=16&item=shoes&price=100

使用如下的代码来查看请求参数。req.URL.Query()的返回值是Values类型,这个类型实际上是type Values map[string][]string,因此我们可以遍历这个map。

func (db database) update(w http.ResponseWriter, req *http.Request) {
    query := req.URL.Query()
    for key, item := range query {
        fmt.Fprintln(w, key, item)
    }
}

遍历map后得到的结果如图所示。从图中可以看出map类型的query变量有两项,分别是item [socks shoes]和price [16 100]。socks对应16,shoes对应100。拿到待更新的值后就可以更新对应的变量啦!

caf55f3add7953d860b659caae0f6b42.png

有疑问加站长微信联系(非本文作者)

280

本文来自:简书

感谢作者:yufeifly

查看原文:golang 如何解析url中的多个参数

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:701969077


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK