美文网首页beego
Go Session5:beego/session的应用

Go Session5:beego/session的应用

作者: 副班长国伟 | 来源:发表于2018-06-22 12:19 被阅读0次

    项目目录树结构

    mysession项目目录树结构

    main.go

    import (

        "fmt"

        _ "mysession/routers"

        "github.com/astaxie/beego"

    )

    func init() {

        fmt.Println("Init.")

    }

    func main() {

        fmt.Println("Main.")

        beego.BConfig.WebConfig.Session.SessionOn = true

        beego.Run()

    }

    login.go

    import (

        "fmt"

        "github.com/astaxie/beego"

    )

    type LoginController struct {

        beego.Controller

    }

    func (c *LoginController) Get() {

        fmt.Println("Login Get.")

        c.TplName = "login.html"

    }

    func (c *LoginController) Post() {

        fmt.Println("Login Post.")

        name := c.GetString("name")

        pwd := c.GetString("pwd")

        isLogin := 0

        if name == "admin" && pwd == "123456" {

            c.SetSession("loginuser", "adminuser")

            fmt.Println("session:", c.CruSession)

        } else if name != "admin" {

            isLogin = 1

        } else if pwd != "123456" {

            isLogin = 2

        }

        fmt.Println("isLogin", isLogin)

        c.Data["json"] = map[string]interface{}{"islogin": isLogin}

        c.ServeJSON()

    }

    type LogoutController struct {

        beego.Controller

    }

    func (c *LogoutController) Post() {

        v := c.GetSession("loginuser")

        fmt.Println("v", v)

        isLogin := false

        if v != nil {

            c.DelSession("loginuser")

            c.DestroySession()

            isLogin = true

            fmt.Println("session:", c.CruSession)

        }

        c.Data["json"] = map[string]interface{}{"islogin": isLogin}

        c.ServeJSON()

    }

    routers.go

    import (

        "mysession/controllers"

        "github.com/astaxie/beego"

    )

    func init() {

        beego.Router("/login", &controllers.LoginController{})

        beego.Router("/logout", &controllers.LogoutController{})

    }

    app.conf

    appname = mysession

    httpport = 8081

    runmode = dev

    login.html

    https://github.com/weiyunhelong/BeegoLearn/blob/master/views/login.html

    运行

    浏览器输入:http://localhost:8081/login

    运行结果:

    相关文章

      网友评论

        本文标题:Go Session5:beego/session的应用

        本文链接:https://www.haomeiwen.com/subject/hnxhyftx.html