Help us understand the problem. What is going on with this article?

Go - irisとgorilla/sessionsでセッション管理してみる

More than 3 years have passed since last update.

irisについてるセッション管理ライブラリを使うと、どうもロック関連がおかしくて途中で止まってしまうので、gorilla/sessionを使ってみる。

カウンターつくってみた。/upにアクセスすると1アップして、/clにアクセスするとクリアされる。

コード

main.go
package main

import (
    "github.com/kataras/iris"
    "github.com/kataras/iris/context"
    "github.com/gorilla/sessions"
    "fmt"
)

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 (
    "github.com/kataras/iris/context"
    "fmt"
)

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())
}

画面

session.png

edo1z
最近はPHPとVue.jsとFirebaseを使うことが多いです
https://twitter.com/edo1z
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away