合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
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 ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <form action='#' method="post" enctype="multipart/form-data"> <div class="field-content"> User Name:<input name="user_name" value="{{.Name}}" type="text" /> </div> <div class="field-content"> Password:<input name="user_pwd" value="{{.Pwd}}" type="password" /> </div> <div class="field-content"> <input type="submit" value="提交" /> </div> </form> </body> </html> ~~~