2.session 包使用
最后更新于:2022-04-02 04:54:25
beego session包
代码实例:
main.go
~~~
package main
import (
"fmt"
"html/template"
"io"
"net/http"
"github.com/astaxie/beego/session"
)
var globalSessions *session.Manager
func init() {
managerConfig := session.ManagerConfig{
CookieName: "cookie",
EnableSetCookie: true,
Gclifetime: 3600,
Maxlifetime: 3600,
Secure: false,
CookieLifeTime: 3600,
ProviderConfig: "",
}
// 初始化 session
globalSessions, _ = session.NewManager("memory", &managerConfig)
go globalSessions.GC()
}
var myTemplate *template.Template
type Person struct {
Name string
Pwd string
}
func userInfo(w http.ResponseWriter, r *http.Request) {
// 根据当前请求返回 session 对象
sess, _ := globalSessions.SessionStart(w, r)
defer sess.SessionRelease(w)
if r.Method == "GET" {
// 获取 session
username := sess.Get("user_name")
userpwd := sess.Get("user_pwd")
name, errName := username.(string)
pwd, errPwd := userpwd.(string)
if errName && errPwd {
p := Person{Name: name, Pwd: pwd}
myTemplate.Execute(w, p)
} else {
myTemplate.Execute(w, nil)
}
} else {
username := r.FormValue("user_name")
userpwd := r.FormValue("user_pwd")
// 设置 session
sess.Set("user_name", username)
sess.Set("user_pwd", userpwd)
p := Person{Name: username, Pwd: userpwd}
io.WriteString(w, "")
myTemplate.Execute(w, p)
}
}
func initTemplate(fileName string) (err error) {
myTemplate, err = template.ParseFiles(fileName)
if err != nil {
fmt.Println("parse file err:", err)
return
}
return
}
func main() {
initTemplate("./index.html")
http.HandleFunc("/user/info", userInfo)
err := http.ListenAndServe("0.0.0.0:8880", nil)
if err != nil {
fmt.Println("http listen failed")
}
}
~~~
index.html
~~~
Document
~~~
';