如何在Iris中解析查询字符串

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

How to parse query strings in Iris

问题

根据IrisHi示例,我想创建一个应用程序,可以解析如下请求:

wget -qO- "http://localhost:8080/hi?name=John"

并回复Hi John!

以下是我的处理程序代码:

func hi(ctx *iris.Context) {
    name := ctx.ParamDecoded("name")
    ctx.Writef("Hi %s!", name)
}

目前它只回答Hi !,我该如何使其回答Hi John!

英文:

Based on the Hi example for Iris I want to create an application that can parse a request like

wget -qO- "http://localhost:8080/hi?name=John"
and respond with Hi John!.

Here's my handler code:

<!-- language: lang-go -->

func hi(ctx *iris.Context) {
	name := ctx.ParamDecoded(&quot;name&quot;)
	ctx.Writef(&quot;Hi %s!&quot;, name)
}

This just answers Hi ! - how can I make it answer Hi John!

答案1

得分: 0

重要提示:关于是否使用Iris存在争议,因为作者显然多次删除了历史记录,这使得它很难作为一个稳定的API使用。请阅读为什么不应该在Go中使用Iris并形成自己的观点。

只需使用ctx.FormValue(...)而不是ctx.ParamDecoded()

func hi(ctx *iris.Context) {
    name := ctx.FormValue("name")
    ctx.Writef("Hi %s!", name)
}

如果没有这样的表单值(即查询参数)存在,它将返回一个空字符串。

如果您想测试表单值是否实际存在,可以使用ctx.FormValues()获取一个映射。然而,这有点复杂,因为该映射包含每个键的字符串值列表:

func hi(ctx *iris.Context) {
    form := ctx.FormValues()
    names, ok := form["name"]
    name := ""
    if !ok { // 没有name参数
        name = "<unknown>"
    } else { // 至少有一个name
        name = names[0]
    }
    ctx.Writef("Hi %s!", name)
}
英文:

Important: There is controversy about whether to use Iris at all as the author apparently deleted the history multiple times, which makes it hard to use as a stable API. Please read Why you should not use Iris for your Go and form your own opinion

Just use ctx.FormValue(...) instead of ctx.ParamDecoded():

func hi(ctx *iris.Context) {
	name := ctx.FormValue(&quot;name&quot;)
	ctx.Writef(&quot;Hi %s!&quot;, name)
}

If there is no such form value (i.e. query parameter) present, this will just return an empty string.

If you want to test whether a form value is actually present, you can use ctx.FormValues() to obtain a map. This is a little bit more complex, however, because the map contains a list of string values for each key:

<!-- language: lang-go -->

func hi(ctx *iris.Context) {
	form := ctx.FormValues()
	names, ok := form[&quot;name&quot;]
	name := &quot;&quot;
	if !ok { // No name parameter
		name = &quot;&lt;unknown&gt;&quot;
	} else { // At least one name
		name = names[0]
	}
	ctx.Writef(&quot;Hi %s!&quot;, name)
}

答案2

得分: 0

func hi(ctx *iris.Context) {
    name := ctx.URLParam("name")
    ctx.Writef("Hi %s!", name)
}

<details>
<summary>英文:</summary>

func hi(ctx *iris.Context) {
name := ctx.URLParam("name")
ctx.Writef("Hi %s!", name)
}


</details>



huangapple
  • 本文由 发表于 2017年1月27日 07:26:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/41884806.html
匿名

发表评论

匿名网友

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

确定