Go Session5:beego/session的应用

项目目录树结构

Go Session5:beego/session的应用_第1张图片
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的应用_第2张图片

你可能感兴趣的:(Go Session5:beego/session的应用)