首页 文章

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

提问于
浏览
0

基于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!

1 回答

  • 0

    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

    只需使用 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 { // No name parameter
            name = "<unknown>"
        } else { // At least one name
            name = names[0]
        }
        ctx.Writef("Hi %s!", name)
    }
    

相关问题