├── go.mod ├── .gitignore ├── .travis.yml ├── session ├── cache │ ├── cache_conf.go │ ├── cache.go │ └── session.go ├── redis │ ├── redis_conf.go │ ├── redis.go │ └── session.go └── utils │ └── utils.go ├── LICENSE └── README.md /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/karldoenitz/tission 2 | 3 | require ( 4 | github.com/gomodule/redigo v2.0.0+incompatible 5 | github.com/karldoenitz/Tigo v1.6.6 6 | github.com/patrickmn/go-cache v2.1.0+incompatible 7 | ) 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | matrix: 4 | fast_finish: true 5 | include: 6 | - go: 1.11.x 7 | env: GO111MODULE=on 8 | - go: 1.12.x 9 | env: GO111MODULE=on 10 | - go: 1.13.x 11 | env: GO111MODULE=on 12 | 13 | install: go get github.com/karldoenitz/tission/session/redis 14 | -------------------------------------------------------------------------------- /session/cache/cache_conf.go: -------------------------------------------------------------------------------- 1 | package cache 2 | 3 | import ( 4 | "github.com/patrickmn/go-cache" 5 | "time" 6 | ) 7 | 8 | var cacheManager *cache.Cache 9 | 10 | func produceCacheManager(defaultExpiration, cleanupInterval time.Duration) *cache.Cache { 11 | return cache.New(defaultExpiration, cleanupInterval) 12 | } 13 | -------------------------------------------------------------------------------- /session/cache/cache.go: -------------------------------------------------------------------------------- 1 | package cache 2 | 3 | import "time" 4 | 5 | func Set(key string, value interface{}, lifeTime time.Duration) (err error) { 6 | cache := si.GetCache() 7 | err = cache.Add(key, value, lifeTime) 8 | return 9 | } 10 | 11 | func Get(key string) (data interface{}, found bool) { 12 | cache := si.GetCache() 13 | data, found = cache.Get(key) 14 | return 15 | } 16 | 17 | func Del(key string) { 18 | cache := si.GetCache() 19 | cache.Delete(key) 20 | } 21 | -------------------------------------------------------------------------------- /session/redis/redis_conf.go: -------------------------------------------------------------------------------- 1 | package redis 2 | 3 | import ( 4 | "github.com/gomodule/redigo/redis" 5 | "time" 6 | ) 7 | 8 | var redisPool *redis.Pool 9 | 10 | func produceRedisPool(addr string, maxIdle, timeout int, auth string, dbNo interface{}, pwd string) *redis.Pool { 11 | return &redis.Pool{ 12 | MaxIdle: maxIdle, 13 | IdleTimeout: time.Duration(timeout) * time.Second, 14 | Dial: func() (redis.Conn, error) { 15 | conn, err := redis.Dial("tcp", addr, redis.DialPassword(pwd), redis.DialDatabase(dbNo.(int))) 16 | if err != nil { 17 | return nil, err 18 | } 19 | return conn, nil 20 | }, 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Karl 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /session/redis/redis.go: -------------------------------------------------------------------------------- 1 | package redis 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "time" 7 | ) 8 | 9 | const DbCacheTime = 3600 * time.Second 10 | 11 | func Set(key string, value interface{}, lifeTime time.Duration) (error, []byte) { 12 | redisPool := si.GetRedisPool() 13 | conn := redisPool.Get() 14 | defer conn.Close() 15 | 16 | var ( 17 | err error 18 | v []byte 19 | ) 20 | switch value.(type) { 21 | case string: 22 | v = []byte(value.(string)) 23 | case []byte: 24 | v = value.([]byte) 25 | default: 26 | v, err = json.Marshal(value) 27 | } 28 | s := lifeTime.Seconds() 29 | _, err = conn.Do("SETEX", key, int(s), v) 30 | if err != nil { 31 | fmt.Println(err.Error()) 32 | fmt.Printf("SETEX key[%s] failed", key) 33 | } 34 | return err, v 35 | } 36 | 37 | func Get(key string) (data []byte, found bool) { 38 | redisPool := si.GetRedisPool() 39 | conn := redisPool.Get() 40 | defer conn.Close() 41 | reply, _ := conn.Do("GET", key) 42 | if reply != nil { 43 | data = reply.([]byte) 44 | found = true 45 | } else { 46 | found = false 47 | } 48 | return 49 | } 50 | 51 | func Del(key string) int64 { 52 | redisPool := si.GetRedisPool() 53 | conn := redisPool.Get() 54 | defer conn.Close() 55 | reply, _ := conn.Do("DEL", key) 56 | return reply.(int64) 57 | } 58 | -------------------------------------------------------------------------------- /session/utils/utils.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "crypto/md5" 5 | "fmt" 6 | "net" 7 | "runtime" 8 | "strconv" 9 | "strings" 10 | "time" 11 | ) 12 | 13 | func getGoroutineId() int { 14 | var buf [64]byte 15 | n := runtime.Stack(buf[:], false) 16 | idField := strings.Fields(strings.TrimPrefix(string(buf[:n]), "goroutine "))[0] 17 | id, err := strconv.Atoi(idField) 18 | if err != nil { 19 | panic(fmt.Sprintf("cannot get goroutine id: %v", err)) 20 | } 21 | return id 22 | } 23 | 24 | // getLocalIP returns the non loopback local IP of the host 25 | func getLocalIP() string { 26 | addrs, err := net.InterfaceAddrs() 27 | if err != nil { 28 | return "" 29 | } 30 | for _, address := range addrs { 31 | // check the address type and if it is not a loopback the display it 32 | if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { 33 | if ipnet.IP.To4() != nil { 34 | return ipnet.IP.String() 35 | } 36 | } 37 | } 38 | return "" 39 | } 40 | 41 | func toMd5(original string) string { 42 | bytes := []byte(original) 43 | has := md5.Sum(bytes) 44 | return fmt.Sprintf("%X", has) 45 | } 46 | 47 | func GetSessionId() string { 48 | ip := getLocalIP() 49 | goId := getGoroutineId() 50 | timeStamp := time.Now().Local().Unix() 51 | origin := fmt.Sprintf("%s-%d-%d", ip, goId, timeStamp) 52 | return toMd5(origin) 53 | } 54 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Badge](https://img.shields.io/badge/link-Tigo-blue.svg)](https://karldoenitz.github.io/Tigo/) 2 | [![LICENSE](https://img.shields.io/badge/license-tission-blue.svg)](https://github.com/karldoenitz/tission/blob/master/LICENSE) 3 | [![Build Status](https://travis-ci.org/karldoenitz/tission.svg?branch=master)](https://travis-ci.org/karldoenitz/tission) 4 | # tission 5 | 6 | 一个基于redis实现的session处理插件,可内嵌入`Tigo`框架使用。 7 | 8 | ## 安装 9 | 10 | ```shell 11 | go get github.com/karldoenitz/tission 12 | ``` 13 | 14 | ## 使用 15 | 16 | 将此包引入到`Tigo`项目中,简单配置之后即可使用,Demo如下所示: 17 | 18 | ```go 19 | package main 20 | 21 | import ( 22 | "fmt" 23 | "github.com/karldoenitz/Tigo/TigoWeb" 24 | "github.com/karldoenitz/tission/session/redis" 25 | ) 26 | 27 | type Test struct { 28 | A string 29 | B string 30 | } 31 | 32 | type FrontHandler struct { 33 | TigoWeb.BaseHandler 34 | } 35 | 36 | func (frontHandler *FrontHandler) Get() { 37 | param := frontHandler.GetParameter("a").ToString() 38 | t := Test{} 39 | if param == "a" { 40 | frontHandler.GetSession("abc", &t) // 从session中取值 41 | frontHandler.ResponseAsJson(t) 42 | return 43 | } 44 | t.A = param 45 | t.B = "from session" 46 | e := frontHandler.SetSession("abc", t) // 设置session值 47 | if e != nil { 48 | fmt.Println(e.Error()) 49 | } 50 | frontHandler.ResponseAsJson(t) 51 | } 52 | 53 | type Testa struct { 54 | TigoWeb.BaseHandler 55 | } 56 | 57 | func (t * Testa) Get() { 58 | param := t.GetParameter("a").ToString() 59 | if param == "a" { 60 | tt := Test{} 61 | if e := t.GetSession("abc", &tt); e != nil { 62 | println(e.Error()) 63 | } 64 | t.ResponseAsJson(tt) 65 | return 66 | } 67 | } 68 | 69 | var urlMapping = []TigoWeb.Router{ 70 | {"/front", &FrontHandler{}, nil}, 71 | {"/tt", &Testa{}, nil}, 72 | } 73 | 74 | func main() { 75 | application := TigoWeb.Application{IPAddress: "0.0.0.0", Port: 8888, UrlRouters: urlMapping} 76 | t := redis.SessionInterface{ 77 | IP: "127.0.0.1", // redis地址 78 | Port: "6379", // redis端口 79 | MaxIdle: 10, 80 | Timeout: 100, 81 | Expire: 3600, // 3600s后session过期 82 | } 83 | application.StartSession(&t, "tid") 84 | application.Run() 85 | } 86 | ``` 87 | 88 | -------------------------------------------------------------------------------- /session/cache/session.go: -------------------------------------------------------------------------------- 1 | package cache 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "github.com/karldoenitz/Tigo/TigoWeb" 8 | "github.com/karldoenitz/tission/session/utils" 9 | "github.com/patrickmn/go-cache" 10 | "reflect" 11 | "time" 12 | ) 13 | 14 | var ( 15 | si SessionInterface 16 | ) 17 | 18 | type SessionInterface struct { 19 | Expire time.Duration 20 | } 21 | 22 | func (sip *SessionInterface) initCache() { 23 | cacheManager = produceCacheManager(sip.Expire, sip.Expire) 24 | } 25 | 26 | func (sip *SessionInterface) NewSessionManager() TigoWeb.SessionManager { 27 | // 这里初始化缓存 28 | return &SessionManager{expire: sip.Expire} 29 | } 30 | 31 | func (sip *SessionInterface) GetCache() *cache.Cache { 32 | if cacheManager != nil { 33 | return cacheManager 34 | } 35 | sip.initCache() 36 | return cacheManager 37 | } 38 | 39 | type SessionManager struct { 40 | expire time.Duration 41 | } 42 | 43 | func (sm *SessionManager) GenerateSession(expire int) TigoWeb.Session { 44 | session := Session{} 45 | session.sessionId = utils.GetSessionId() 46 | sm.expire = time.Duration(expire) 47 | session.expire = sm.expire 48 | Set(session.sessionId, "", sm.expire) 49 | return &session 50 | } 51 | 52 | func (sm *SessionManager) GetSessionBySid(sid string) TigoWeb.Session { 53 | session := Session{sessionId: sid} 54 | // 从缓存中获取 55 | _, isFound := Get(sid) 56 | if !isFound { 57 | return &session 58 | } 59 | session.sessionId = sid 60 | session.expire = sm.expire 61 | return &session 62 | } 63 | 64 | func (sm *SessionManager) DeleteSession(sid string) { 65 | Del(sid) 66 | } 67 | 68 | type Session struct { 69 | sessionId string 70 | expire time.Duration 71 | } 72 | 73 | func (s *Session) updateSession() (err error) { 74 | // 向缓存中设置 75 | if err := Set(s.sessionId, "", s.expire); err != nil { 76 | fmt.Println(err.Error()) 77 | } 78 | return 79 | } 80 | 81 | func (s *Session) Get(key string, value interface{}) (err error) { 82 | defer func() { 83 | fatalError := recover() 84 | if fatalError != nil { 85 | err = errors.New(fmt.Sprintf("session值类型与返回值不匹配: error(%#v)", fatalError)) 86 | return 87 | } 88 | }() 89 | sessionKey := fmt.Sprintf("tission_%s_%s", s.sessionId, key) 90 | sv, isExisted := Get(sessionKey) 91 | if !isExisted { 92 | return errors.New(fmt.Sprintf("session value of key(%s) is nil", key)) 93 | } 94 | valPtr := reflect.ValueOf(value).Elem() 95 | switch valPtr.Type().Kind() { 96 | case reflect.String: 97 | v := sv.(string) 98 | valPtr.SetString(v) 99 | case reflect.Bool: 100 | v := sv.(bool) 101 | valPtr.SetBool(v) 102 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 103 | v := sv.(uint64) 104 | valPtr.SetUint(v) 105 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 106 | v := sv.(int64) 107 | valPtr.SetInt(v) 108 | case reflect.Float32, reflect.Float64: 109 | v := sv.(float64) 110 | valPtr.SetFloat(v) 111 | case reflect.Map, reflect.Slice, reflect.Struct: 112 | b, e := json.Marshal(sv) 113 | if e != nil { 114 | return e 115 | } 116 | if e := json.Unmarshal(b, value); e != nil { 117 | return e 118 | } 119 | } 120 | return 121 | } 122 | 123 | func (s *Session) Set(key string, value interface{}) (err error) { 124 | sessionKey := fmt.Sprintf("tission_%s_%s", s.sessionId, key) 125 | if err := Set(sessionKey, value, s.expire); err != nil { 126 | fmt.Printf("set %s %v to session failed => %s", key, value, err.Error()) 127 | } 128 | return s.updateSession() 129 | } 130 | 131 | func (s *Session) Delete(key string) { 132 | sessionKey := fmt.Sprintf("tission_%s_%s", s.sessionId, key) 133 | Del(sessionKey) 134 | _ = s.updateSession() 135 | } 136 | 137 | func (s *Session) SessionId() (sid string) { 138 | return s.sessionId 139 | } 140 | -------------------------------------------------------------------------------- /session/redis/session.go: -------------------------------------------------------------------------------- 1 | package redis 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "github.com/gomodule/redigo/redis" 8 | "github.com/karldoenitz/Tigo/TigoWeb" 9 | "github.com/karldoenitz/tission/session/utils" 10 | "reflect" 11 | "time" 12 | ) 13 | 14 | var si SessionInterface 15 | 16 | var ( 17 | IP string 18 | Port string 19 | MaxIdle int 20 | Timeout int 21 | Pwd string 22 | Auth string 23 | DbNo int 24 | ) 25 | 26 | type SessionInterface struct { 27 | IP string 28 | Port string 29 | MaxIdle int 30 | Timeout int 31 | Pwd string 32 | Auth string 33 | DbNo int 34 | Expire int64 35 | } 36 | 37 | func (sip *SessionInterface) initRedisPool() { 38 | addr := fmt.Sprintf("%s:%s", IP, Port) 39 | redisPool = produceRedisPool(addr, MaxIdle, Timeout, Auth, DbNo, Pwd) 40 | } 41 | 42 | func (sip *SessionInterface) GetRedisPool() *redis.Pool { 43 | if redisPool != nil { 44 | return redisPool 45 | } 46 | sip.initRedisPool() 47 | return redisPool 48 | } 49 | 50 | func (sip *SessionInterface) NewSessionManager() TigoWeb.SessionManager { 51 | IP = sip.IP 52 | Port = sip.Port 53 | MaxIdle = sip.MaxIdle 54 | Timeout = sip.Timeout 55 | Pwd = sip.Pwd 56 | Auth = sip.Auth 57 | DbNo = sip.DbNo 58 | sip.initRedisPool() 59 | return &SessionManager{expire: sip.Expire} 60 | } 61 | 62 | type SessionManager struct { 63 | expire int64 64 | } 65 | 66 | func (sm *SessionManager) GenerateSession(expire int) TigoWeb.Session { 67 | session := Session{} 68 | session.sessionId = utils.GetSessionId() 69 | session.value = make(map[string]interface{}) 70 | if expire == 0 { 71 | sm.expire = int64(expire) * int64(time.Second) 72 | } 73 | session.expire = sm.expire 74 | Set(session.sessionId, session.value, time.Duration(sm.expire)) 75 | return &session 76 | } 77 | 78 | func (sm *SessionManager) GetSessionBySid(sid string) TigoWeb.Session { 79 | session := Session{} 80 | value, isFound := Get(sid) 81 | if !isFound { 82 | return &session 83 | } 84 | session.sessionId = sid 85 | session.value = make(map[string]interface{}) 86 | session.expire = sm.expire 87 | if session.expire == 0 { 88 | session.expire = int64(3600) * int64(time.Second) 89 | } 90 | json.Unmarshal(value, &(session.value)) 91 | return &session 92 | } 93 | 94 | func (sm *SessionManager) DeleteSession(sid string) { 95 | Del(sid) 96 | } 97 | 98 | type Session struct { 99 | value map[string]interface{} 100 | sessionId string 101 | expire int64 102 | } 103 | 104 | func (s *Session) updateSession() (err error) { 105 | data, err := json.Marshal(s.value) 106 | if err != nil { 107 | fmt.Println(err.Error()) 108 | return 109 | } 110 | if err, _ := Set(s.sessionId, data, time.Duration(s.expire)); err != nil { 111 | fmt.Println(err.Error()) 112 | } 113 | return 114 | } 115 | 116 | func (s *Session) Get(key string, value interface{}) (err error) { 117 | defer func() { 118 | fatalError := recover() 119 | if fatalError != nil { 120 | err = errors.New(fmt.Sprintf("session值类型与返回值不匹配: error(%#v)", fatalError)) 121 | return 122 | } 123 | }() 124 | sv, isExisted := s.value[key] 125 | if !isExisted { 126 | return errors.New(fmt.Sprintf("session value of key(%s) is nil", key)) 127 | } 128 | valPtr := reflect.ValueOf(value).Elem() 129 | switch valPtr.Kind() { 130 | case reflect.String: 131 | v := sv.(string) 132 | valPtr.SetString(v) 133 | case reflect.Bool: 134 | v := sv.(bool) 135 | valPtr.SetBool(v) 136 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 137 | v := sv.(float64) 138 | valPtr.SetUint(uint64(v)) 139 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 140 | v := sv.(float64) 141 | valPtr.SetInt(int64(v)) 142 | case reflect.Float32, reflect.Float64: 143 | v := sv.(float64) 144 | valPtr.SetFloat(v) 145 | case reflect.Map, reflect.Slice, reflect.Struct: 146 | b, e := json.Marshal(sv) 147 | if e != nil { 148 | return e 149 | } 150 | if e := json.Unmarshal(b, value); e != nil { 151 | return e 152 | } 153 | } 154 | return 155 | } 156 | 157 | func (s *Session) Set(key string, value interface{}) (err error) { 158 | s.value[key] = value 159 | return s.updateSession() 160 | } 161 | 162 | func (s *Session) Delete(key string) { 163 | if _, isExisted := s.value[key]; isExisted { 164 | delete(s.value, key) 165 | } 166 | s.updateSession() 167 | } 168 | 169 | func (s *Session) SessionId() (sid string) { 170 | return s.sessionId 171 | } 172 | --------------------------------------------------------------------------------