Go实战--Gorilla web toolkit使用之gorilla/sessions(iris+sessions)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangshubo1989/article/details/78921468

生命不止,继续go go go!!!
昨天介绍了:
Go实战–Gorilla web toolkit使用之gorilla/context

今天介绍gorilla/sessions:
Package sessions provides cookie and filesystem sessions and infrastructure for custom session backends.

特性:
* Simple API: use it as an easy way to set signed (and optionally
encrypted) cookies.
* Built-in backends to store sessions in cookies or the filesystem.
* Flash messages: session values that last until read.
* Convenient way to switch session persistency (aka “remember me”) and set
other attributes.
* Mechanism to rotate authentication and encryption keys.
* Multiple sessions per request, even using different backends.
* Interfaces and infrastructure for custom session backends: sessions from
different stores can be retrieved and batch-saved using a common API.

官网:
http://www.gorillatoolkit.org/pkg/sessions

获取:
go get github.com/gorilla/sessions

API:
这里写图片描述

应用
gorilla/mux + gorilla/sessions

package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/gorilla/sessions"
)

var store = sessions.NewCookieStore([]byte("something-very-secret"))

func MyHandler(w http.ResponseWriter, r *http.Request) {

    session, err := store.Get(r, "s1")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    fmt.Println(session)
    session.Values["name"] = "spuerWang"
    session.Save(r, w)
}

func main() {

    routes := mux.NewRouter()
    routes.HandleFunc("/session", MyHandler)
    http.Handle("/", routes)
    http.ListenAndServe(":8080", nil)
}

浏览器输入:
http://localhost:8080/session

&{ map[] 0xc0420f61b0 true 0xc0420c0d00 s1}

这里写图片描述

iris+gorilla/sessions
iris框架不会陌生,之前也有介绍奥:
这里写图片描述

https://qiita.com/edo1z/items/ff47d04b6cdd4b0de64c

main.go

package main

import (
    "fmt"

    "github.com/gorilla/sessions"
    "github.com/kataras/iris"
    "github.com/kataras/iris/context"
)

var store = sessions.NewCookieStore([]byte("hoge"))
var sess_name = "sess"

func main() {
    app := iris.New()
    app.Get("/", topPage)
    app.Get("up", upPage)
    app.Get("cl", clearPage)
    app.Run(iris.Addr(":8080"))
}

func topPage(ctx context.Context) {
    f := getFlash(ctx)
    cnt := fmt.Sprintf(
        "<h2>count is %d</h2>",
        getCount(ctx),
    )
    html := `<br><a href="/up">Count Up</a>
    <br><a href="/cl">Count Clear</a>`
    ctx.HTML(f + cnt + html)
}

func upPage(ctx context.Context) {
    countUp(ctx)
    addFlash(ctx, "count up")
    ctx.Redirect("/")
}

func clearPage(ctx context.Context) {
    sessClear(ctx)
    addFlash(ctx, "session clear")
    ctx.Redirect("/")
}

session.go

package main

import (
    "fmt"

    "github.com/kataras/iris/context"
)

func getCount(ctx context.Context) int {
    sess, _ := store.Get(ctx.Request(), sess_name)
    cnt := 0
    if v, ok := sess.Values["cnt"]; ok {
        if c, ok := v.(int); ok {
            cnt = c
        }
    }
    return cnt
}

func countUp(ctx context.Context) {
    sess, _ := store.Get(ctx.Request(), sess_name)
    cnt := 1
    if v, ok := sess.Values["cnt"]; ok {
        if c, ok := v.(int); ok {
            cnt = c + 1
        }
    }
    sess.Values["cnt"] = cnt
    sess.Save(ctx.Request(), ctx.ResponseWriter())
}

func sessClear(ctx context.Context) {
    sess, _ := store.Get(ctx.Request(), sess_name)
    sess.Values = make(map[interface{}]interface{})
    sess.Save(ctx.Request(), ctx.ResponseWriter())
}

func getFlash(ctx context.Context) string {
    sess, _ := store.Get(ctx.Request(), sess_name)
    f := sess.Flashes()
    sess.Save(ctx.Request(), ctx.ResponseWriter())
    if len(f) > 0 {
        return fmt.Sprintf(
            `<p style="color:#090;padding:5px;">%s</p>`,
            f[0],
        )
    }
    return ""
}

func addFlash(ctx context.Context, msg string) {
    sess, _ := store.Get(ctx.Request(), sess_name)
    sess.AddFlash(msg)
    sess.Save(ctx.Request(), ctx.ResponseWriter())
}

这里写图片描述

猜你喜欢

转载自blog.csdn.net/wangshubo1989/article/details/78921468