IRIS 框架 WEBAPI 参数风格 url/?param=value 如何优雅使用

IRIS框架 WEBAPI 参数风格

url/?param=value风格参数

Iris使用URL参数时,传统是“URL/value/”风格,有没有办法可以使用“url/?param=value”风格,传统的“?”连接风格的方式?
如下代码:

services.Get("/test", func(ctx iris.Context) {
    w := ctx.Request()
    vars := w.URL.Query()
    user := vars["user"][0]
    //user := ctx.Params().Get("user")
    ctx.WriteString(user)
})

目前用iris.Context中的Request()转换成非Iris的方式,用URL.Query()来获取参数,但感觉不够优雅。有没有办法在做路由时通过路由地址的正则或何种方式比较优雅的实现?
谢谢大家的帮助

最佳答案
package main

import (
    "github.com/kataras/iris/v12"
)

type MyType struct {
    Name string `url:"name"`
    Age  int    `url:"age"`
}

func main() {
    app := iris.New()

    app.Get("/", func(ctx iris.Context) {
        var t MyType
        err := ctx.ReadQuery(&t)
        if err != nil && !iris.IsErrPath(err) {
            ctx.StatusCode(iris.StatusInternalServerError)
            ctx.WriteString(err.Error())
        }

        ctx.Writef("MyType: %#v", t)
    })

    // http://localhost:8080?name=iris&age=3
    app.Run(iris.Addr(":8080"))
}

希望可以帮到你 :see_no_evil:

4年前 评论
lossage (楼主) 4年前
snowlyg (作者) 4年前
讨论数量: 3
shubiao-yao

建议遵循框架的规范,你说的这个框架我没接触过,目前正在使用gin框架,跟你描述这个情况差不多。

4年前 评论

谢谢。因为有和别的软件对接,该软件固定了?风格的参数传递方式。想寻求一下优雅的使用方法

4年前 评论
package main

import (
    "github.com/kataras/iris/v12"
)

type MyType struct {
    Name string `url:"name"`
    Age  int    `url:"age"`
}

func main() {
    app := iris.New()

    app.Get("/", func(ctx iris.Context) {
        var t MyType
        err := ctx.ReadQuery(&t)
        if err != nil && !iris.IsErrPath(err) {
            ctx.StatusCode(iris.StatusInternalServerError)
            ctx.WriteString(err.Error())
        }

        ctx.Writef("MyType: %#v", t)
    })

    // http://localhost:8080?name=iris&age=3
    app.Run(iris.Addr(":8080"))
}

希望可以帮到你 :see_no_evil:

4年前 评论
lossage (楼主) 4年前
snowlyg (作者) 4年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!