From b1e8e839cd7836e7d21c96c2b30693909f6908f7 Mon Sep 17 00:00:00 2001 From: qydysky Date: Sat, 31 Oct 2020 17:12:26 +0800 Subject: [PATCH] 89 --- Session.go => session/Session.go | 35 ++++++++++++++++++-------------- session/Session_test.go | 15 ++++++++++++++ 2 files changed, 35 insertions(+), 15 deletions(-) rename Session.go => session/Session.go (58%) create mode 100644 session/Session_test.go diff --git a/Session.go b/session/Session.go similarity index 58% rename from Session.go rename to session/Session.go index 9ee1f38..99e23f0 100644 --- a/Session.go +++ b/session/Session.go @@ -2,46 +2,51 @@ package part import ( "time" + "errors" "strconv" ) -type session struct {} - -const ( - session_SumInTimeout int64 = 1e5 - session_Timeout int64 = 1 -) +type session struct { + SumInTimeout int64 + Timeout int64 + session_now int64 +} var ( session_ks map[string]string = make(map[string]string) session_kt map[string]int64 = make(map[string]int64) session_rand int64 = 1 - session_now int64 session_stop chan bool = make(chan bool,1) ) -func Session() (*session) { - if session_now == 0 { +func Session(SumInTimeout,Timeout int64) (*session,error) { + if SumInTimeout == 0 {return &session{},errors.New("SumInTimeout == 0")} + if Timeout == 0 {return &session{},errors.New("Timeout == 0")} + + s := new(session) + + if s.session_now == 0 { go func(){ for{ - session_now = time.Now().Unix() + s.session_now = time.Now().Unix() time.Sleep(time.Second) } }() } - return &session{} + + return s,nil } func (s *session) Set(key string) (val string) { session_stop <- true - if session_rand >= session_SumInTimeout {session_rand = 1}else{session_rand += 1} + if session_rand >= s.SumInTimeout {session_rand = 1}else{session_rand += 1} t := strconv.FormatInt(session_rand, 10) session_ks[t] = key - session_kt[t] = session_now + session_kt[t] = s.session_now <-session_stop return t @@ -53,7 +58,7 @@ func (s *session) Get(val string) (ok bool,key string){ if !oks {return false,""} T, _ := session_kt[val] - return session_now-T <= session_Timeout, K + return s.session_now-T <= s.Timeout, K } func (s *session) Check(val string,key string) bool { @@ -62,5 +67,5 @@ func (s *session) Check(val string,key string) bool { } func (s *session) Buf() (int64,int) { - return session_now,len(session_ks) + return s.session_now,len(session_ks) } diff --git a/session/Session_test.go b/session/Session_test.go new file mode 100644 index 0000000..2104be6 --- /dev/null +++ b/session/Session_test.go @@ -0,0 +1,15 @@ +package part + +import ( + "time" + "testing" +) + +func Test_session(t *testing.T) { + s,e := Session(1e6, 1) + if e != nil {return} + v := s.Set("a") + if o,p := s.Buf();p != 1 || o - time.Now().Unix() > 1{return} + if ok,k := s.Get(v);!ok || k != "a" {return} + if !s.Check(v, "a") {return} +} -- 2.39.2