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

How to parse query strings in Iris

基于Hi example for Iris我想创建一个可以解析像

这样的请求的应用程序

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!

重要提示:关于是否使用 Iris 存在争议,因为作者显然多次删除了历史记录,这使得它很难用作稳定 API。请阅读Why you should not use Iris for your Go并形成你自己的意见

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

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

如果不存在这样的表单值(即查询参数),这将只是 return 一个空字符串。

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

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