main
// main project main.gopackage mainimport ( "fmt" "HTML/template" "log" "net/http" "strings" "session" _"memory" "time")func sayHelloname(w http.ResponseWriter,r *http.Request) { r.ParseForm() fmt.Println(r.Form) fmt.Println(r.URL.Path) fmt.Println(r.URL.Scheme) fmt.Println(r.Form["url_long"]) for k,v := range r.Form { fmt.Println("key: ",k) fmt.Println("value:",strings.Join(v,"")) } fmt.Fprintln(w,"hello nihao")}func login(w http.ResponseWriter,r *http.Request) { r.ParseForm() fmt.Println("method: ",r.Method) if r.Method == "GET" { t,err := template.Parsefiles("src/HTML/login.gtpl") if err != nil { fmt.Println(err) return } t.Execute(w,nil) } else { fmt.Println("username: ",r.Form["username"]) fmt.Println("password: ",r.Form["password"]) }}func login2(w http.ResponseWriter,r *http.Request) { sess := globalSessions.SessionStart(w,r) r.ParseForm() if r.Method == "GET" { t,_ := template.Parsefiles("src/HTML/login.gtpl") //w.header().Set("Content-Type","text/HTML") t.Execute(w,sess.Get("username")) } else { sess.Set("username",r.Form["username"]) http.Redirect(w,r,"/",302) }}func count(w http.ResponseWriter,r) createtime := sess.Get("createtime") if createtime == nil { sess.Set("createtime",time.Now().Unix()) } else if (createtime.(int64) + 360) < (time.Now().Unix()) { globalSessions.SessionDestroy(w,r) sess = globalSessions.SessionStart(w,r) } ct := sess.Get("countnum") if ct == nil { sess.Set("countnum",1) } else { sess.Set("countnum",(ct.(int) + 1)) } t,_ := template.Parsefiles("count.gtpl") w.header().Set("Content-Type","text/HTML") t.Execute(w,sess.Get("countnum"))}func main() { //http.HandleFunc("/",sayHelloname); http.HandleFunc("/login",login) http.HandleFunc("/login2",login2) err := http.ListenAndServe(":9090",nil) if err != nil { log.Fatalf("Listen and server",err) }}var globalSessions *session.Managerfunc init() { globalSessions,_ = session.NewSessionManager("memory","goSessionID",3600) go globalSessions.GC() fmt.Println("fd")}
session
package sessionimport ( "crypto/rand" "enCoding/base64" "fmt" "io" "net/http" "net/url" "sync" "time")type Manager struct { cookiename string lock sync.Mutex provIDer ProvIDer maxlifeTime int64}type ProvIDer interface { SessionInit(sID string) (Session,error) SessionRead(sID string) (Session,error) SessionDestroy(sID string) error SessionGC(maxlifeTime int64)}type Session interface { Set(key,value interface{}) error Get(key interface{}) interface{} Delete(ket interface{}) error SessionID() string}func NewSessionManager(provIDename,cookiename string,maxlifeTime int64) (*Manager,error) { provIDe,ok := provIDes[provIDename] if !ok { return nil,fmt.Errorf("session: unkNown provIDe %q (forgotten import?",provIDename) } return &Manager{cookiename: cookiename,provIDer: provIDe,maxlifeTime: maxlifeTime},nil}func Register(name string,provIDe ProvIDer) { if provIDe == nil { panic("session: Register provIDe is nil") } if _,dup := provIDes[name]; dup { panic("session: Register called twice for provIDe " + name) } provIDes[name] = provIDe}var provIDes = make(map[string]ProvIDer)func (manager *Manager) sessionID() string { b := make([]byte,32) if _,err := io.ReadFull(rand.Reader,b); err != nil { return "" } return base64.URLEnCoding.EncodetoString(b)}func (manager *Manager) SessionStart(w http.ResponseWriter,r *http.Request) (session Session) { manager.lock.Lock() defer manager.lock.Unlock() cookie,err := r.cookie(manager.cookiename) if err != nil || cookie.Value == "" { sID := manager.sessionID() session,_ = manager.provIDer.SessionInit(sID) cookie := http.cookie{name: manager.cookiename,Value: url.queryEscape(sID),Path: "/",httpOnly: true,MaxAge: int(manager.maxlifeTime)} http.setcookie(w,&cookie) } else { sID,_ := url.queryUnescape(cookie.Value) session,_ = manager.provIDer.SessionRead(sID) } return session}func (manager *Manager) SessionDestroy(w http.ResponseWriter,r *http.Request){ cookie,err := r.cookie(manager.cookiename) if err != nil || cookie.Value == "" { return } else { manager.lock.Lock() defer manager.lock.Unlock() manager.provIDer.SessionDestroy(cookie.Value) expiration := time.Now() cookie := http.cookie{name: manager.cookiename,Expires: expiration,MaxAge: -1} http.setcookie(w,&cookie) }}func (manager *Manager) GC() { manager.lock.Lock() defer manager.lock.Unlock() manager.provIDer.SessionGC(manager.maxlifeTime) time.AfterFunc(time.Duration(manager.maxlifeTime),func(){ manager.GC() })}
memory
package memoryimport ( "container/List" "time" "sync" "fmt" "session")type SessionStore struct { sID string //session ID 唯一标示 timeAccessed time.Time //最后访问时间 value map[interface{}]interface{} //session 里面存储的值}func (st *SessionStore) Set(key,value interface{}) error { st.value[key] = value pder.SessionUpdate(st.sID) return nil}func (st *SessionStore) Get(key interface{}) interface{} { pder.SessionUpdate(st.sID) if v,ok := st.value[key]; ok { return v } else { return nil } return nil}func (st *SessionStore) Delete(key interface{}) error { delete(st.value,key) pder.SessionUpdate(st.sID) return nil}func (st *SessionStore) SessionID() string { return st.sID}type ProvIDer struct { lock sync.Mutex //用来锁 sessions map[string]*List.Element //用来存储在内存 List *List.List //用来做 gc}func (provIDer *ProvIDer) SessionInit(sID string) (session.Session,error) { provIDer.lock.Lock() defer provIDer.lock.Unlock() v := make(map[interface{}]interface{},0) newsess := &SessionStore{sID: sID,timeAccessed: time.Now(),value: v} element := provIDer.List.PushBack(newsess) provIDer.sessions[sID] = element return newsess,nil}func (provIDer *ProvIDer) SessionRead(sID string) (session.Session,error) { if element,ok := provIDer.sessions[sID]; ok { return element.Value.(*SessionStore),nil } else { sess,err := provIDer.SessionInit(sID) return sess,err } return nil,nil}func (provIDer *ProvIDer) SessionDestroy(sID string) error { if element,ok := provIDer.sessions[sID]; ok { delete(provIDer.sessions,sID) provIDer.List.Remove(element) return nil } return nil}func (provIDer *ProvIDer) SessionGC(maxlifeTime int64) { provIDer.lock.Lock() defer provIDer.lock.Unlock() for { element := provIDer.List.Back() if element == nil { break } if (element.Value.(*SessionStore).timeAccessed.Unix() + maxlifeTime) < time.Now().Unix() { provIDer.List.Remove(element) delete(provIDer.sessions,element.Value.(*SessionStore).sID) } else { break } }}func (provIDer *ProvIDer) SessionUpdate(sID string) error { provIDer.lock.Lock() defer provIDer.lock.Unlock() if element,ok := provIDer.sessions[sID]; ok { element.Value.(*SessionStore).timeAccessed = time.Now() provIDer.List.MovetoFront(element) return nil } return nil}var pder = &ProvIDer{List: List.New()}func init() { pder.sessions = make(map[string]*List.Element,0) session.Register("memory",pder) fmt.Println("wzz")}总结
以上是内存溢出为你收集整理的golang cookie与session全部内容,希望文章能够帮你解决golang cookie与session所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)