Cookies

未匹配的标注

众所周知golang官方并没有实现session,但Iris 给出了成熟方案

你在找 http sessions 替代?
下面展示一个使用HTTP Cookies的应用代码

上码

package main

import "github.com/kataras/iris"

func newApp() *iris.Application {
    app := iris.New()

    // 设置Cookie.
    app.Get("/cookies/{name}/{value}", func(ctx iris.Context) {
        name := ctx.Params().Get("name")
        value := ctx.Params().Get("value")

        ctx.SetCookieKV(name, value)

        ctx.Writef("cookie added: %s = %s", name, value)
    })

    // 取值Cookie.
    app.Get("/cookies/{name}", func(ctx iris.Context) {
        name := ctx.Params().Get("name")

        value := ctx.GetCookie(name)

        ctx.WriteString(value)
    })

    // 删除 Cookie.
    app.Delete("/cookies/{name}", func(ctx iris.Context) {
        name := ctx.Params().Get("name")

        ctx.RemoveCookie(name)

        ctx.Writef("cookie %s removed", name)
    })

    return app
}

func main() {
    app := newApp()

    // GET:    http://localhost:8080/cookies/my_name/my_value
    // GET:    http://localhost:8080/cookies/my_name
    // DELETE: http://localhost:8080/cookies/my_name
    app.Run(iris.Addr(":8080"))
}

补充

  • 后补,使用常规 http.Cookiectx.SetCookie(&http.Cookie{...})
  • 自定义Cookie路径 : ctx.SetCookieKV(name, value, iris.CookiePath("/custom/path/cookie/will/be/stored")).
  • 仅让当前请求路径可达 : ctx.SetCookieKV(name, value, iris.CookieCleanPath /* or iris.CookiePath("") */)
    • iris.CookieExpires(time.Duration)
    • iris.CookieHTTPOnly(false)
  • ctx.Request().Cookie(name) 也可用, 使用 net/http 包方式
  • 了解更多的路径参数类型,请点击 这儿.

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
pardon110
讨论数量: 0
发起讨论 只看当前版本


暂无话题~