From d52d96abc2a915dee75ad3d4efa6f43618c07986 Mon Sep 17 00:00:00 2001 From: zhangb Date: Sat, 2 Oct 2021 15:26:29 +0800 Subject: [PATCH] update log and constant --- ChangeLog.md | 5 ++ example/sample/main.go | 15 +++-- example/sample/test/server/server.go | 20 ++++-- example/sample1/main.go | 10 +-- example/sample1/test/server1/server.go | 10 +-- go.mod | 2 +- go.sum | 47 +++++++------- gtoken/gtoken.go | 85 ++++++++++++++------------ gtoken/gtoken_cache.go | 15 +++-- gtoken/gtoken_group.go | 24 ++++---- 10 files changed, 129 insertions(+), 104 deletions(-) diff --git a/ChangeLog.md b/ChangeLog.md index 59e712f..044c834 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,5 +1,10 @@ Change Log 更新说明 ------------------------------ +## 2021-08-25 v1.4.4 +1. 优化框架日志,常量; +2. 启动加入error错误返回,避免异常继续执行; +3. gf升级为v1.16.6,仍没有兼容性问题 + ## 2021-08-25 v1.4.3 1. gf升级为v1.16.5,没有兼容性问题,可以继续使用v1.4.2 2. 处理json转换[]byte打印base64问题 diff --git a/example/sample/main.go b/example/sample/main.go index 7ffe3cf..831bf06 100644 --- a/example/sample/main.go +++ b/example/sample/main.go @@ -4,7 +4,6 @@ import ( "github.com/goflyfox/gtoken/gtoken" "github.com/gogf/gf/frame/g" "github.com/gogf/gf/net/ghttp" - "github.com/gogf/gf/os/glog" ) var TestServerName string @@ -12,13 +11,13 @@ var TestServerName string //var TestServerName string = "gtoken" func main() { - glog.Info("########service start...") + g.Log().Info("########service start...") g.Cfg().SetPath("example/sample") s := g.Server(TestServerName) initRouter(s) - glog.Info("########service finish.") + g.Log().Info("########service finish.") s.Run() } @@ -52,7 +51,10 @@ func initRouter(s *ghttp.Server) { } s.Group("/", func(group *ghttp.RouterGroup) { group.Middleware(CORS) - gfToken.Middleware(group) + err := gfToken.Middleware(group) + if err != nil { + panic(err) + } group.ALL("/system/user", func(r *ghttp.Request) { r.Response.WriteJson(gtoken.Succ("system user")) @@ -80,7 +82,10 @@ func initRouter(s *ghttp.Server) { } s.Group("/admin", func(group *ghttp.RouterGroup) { group.Middleware(CORS) - gfAdminToken.Middleware(group) + err := gfAdminToken.Middleware(group) + if err != nil { + panic(err) + } group.ALL("/system/user", func(r *ghttp.Request) { r.Response.WriteJson(gtoken.Succ("system user")) diff --git a/example/sample/test/server/server.go b/example/sample/test/server/server.go index 7539bc6..8330531 100644 --- a/example/sample/test/server/server.go +++ b/example/sample/test/server/server.go @@ -4,7 +4,6 @@ import ( "github.com/goflyfox/gtoken/gtoken" "github.com/gogf/gf/frame/g" "github.com/gogf/gf/net/ghttp" - "github.com/gogf/gf/os/glog" ) var TestServerName string @@ -14,14 +13,17 @@ var TestServerName string var server *ghttp.Server func Start() { - glog.Info("########service start...") + g.Log().Info("########service start...") g.Cfg().SetPath("../config") server = g.Server(TestServerName) initRouter(server) - glog.Info("########service finish.") - server.Start() + g.Log().Info("########service finish.") + err := server.Start() + if err != nil { + panic(err) + } } func Stop() { @@ -58,7 +60,10 @@ func initRouter(s *ghttp.Server) { } s.Group("/", func(group *ghttp.RouterGroup) { group.Middleware(CORS) - gfToken.Middleware(group) + err := gfToken.Middleware(group) + if err != nil { + panic(err) + } group.ALL("/system/user", func(r *ghttp.Request) { r.Response.WriteJson(gtoken.Succ("system user")) @@ -86,7 +91,10 @@ func initRouter(s *ghttp.Server) { } s.Group("/admin", func(group *ghttp.RouterGroup) { group.Middleware(CORS) - gfAdminToken.Middleware(group) + err := gfAdminToken.Middleware(group) + if err != nil { + panic(err) + } group.ALL("/system/user", func(r *ghttp.Request) { r.Response.WriteJson(gtoken.Succ("system user")) diff --git a/example/sample1/main.go b/example/sample1/main.go index 4bdb0eb..12e0436 100644 --- a/example/sample1/main.go +++ b/example/sample1/main.go @@ -4,7 +4,6 @@ import ( "github.com/goflyfox/gtoken/gtoken" "github.com/gogf/gf/frame/g" "github.com/gogf/gf/net/ghttp" - "github.com/gogf/gf/os/glog" ) var TestServerName string @@ -12,13 +11,13 @@ var TestServerName string //var TestServerName string = "gtoken" func main() { - glog.Info("########service start...") + g.Log().Info("########service start...") g.Cfg().SetPath("example/sample1") s := g.Server(TestServerName) initRouter(s) - glog.Info("########service finish.") + g.Log().Info("########service finish.") s.Run() } @@ -70,7 +69,10 @@ func initRouter(s *ghttp.Server) { AuthExcludePaths: g.SliceStr{"/user/info", "/system/user/info"}, // 不拦截路径 /user/info,/system/user/info,/system/user, GlobalMiddleware: true, // 开启全局拦截 } - gfToken.Start() + err := gfToken.Start() + if err != nil { + panic(err) + } } func Login(r *ghttp.Request) (string, interface{}) { diff --git a/example/sample1/test/server1/server.go b/example/sample1/test/server1/server.go index e124840..d71a81c 100644 --- a/example/sample1/test/server1/server.go +++ b/example/sample1/test/server1/server.go @@ -4,7 +4,6 @@ import ( "github.com/goflyfox/gtoken/gtoken" "github.com/gogf/gf/frame/g" "github.com/gogf/gf/net/ghttp" - "github.com/gogf/gf/os/glog" ) var TestServerName string @@ -14,13 +13,13 @@ var TestServerName string var server *ghttp.Server func Start() { - glog.Info("########service start...") + g.Log().Info("########service start...") g.Cfg().SetPath("../config") server = g.Server(TestServerName) initRouter(server) - glog.Info("########service finish.") + g.Log().Info("########service finish.") server.Start() } @@ -76,7 +75,10 @@ func initRouter(s *ghttp.Server) { AuthExcludePaths: g.SliceStr{"/user/info", "/system/user/info"}, // 不拦截路径 /user/info,/system/user/info,/system/user, GlobalMiddleware: true, // 开启全局拦截 } - gfToken.Start() + err := gfToken.Start() + if err != nil { + panic(err) + } } func Login(r *ghttp.Request) (string, interface{}) { diff --git a/go.mod b/go.mod index ce40d2a..4bb52e4 100644 --- a/go.mod +++ b/go.mod @@ -1,5 +1,5 @@ module github.com/goflyfox/gtoken -require github.com/gogf/gf v1.16.5 +require github.com/gogf/gf v1.16.6 go 1.13 diff --git a/go.sum b/go.sum index 7436343..8eee4a4 100644 --- a/go.sum +++ b/go.sum @@ -8,32 +8,30 @@ github.com/fatih/color v1.12.0 h1:mRhaKNwANqRgUBGKmnI5ZxEk7QXmjQeCcuYFMX2bfcc= github.com/fatih/color v1.12.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= -github.com/gogf/gf v1.16.5 h1:Fh+w+YSbRIGt9nsDcggVLWfMn0Dqemg5rXTtFZRSSpk= -github.com/gogf/gf v1.16.5/go.mod h1:QaYTIiafVdCo5aF/TV/sduU2jLmwJ7JphVCjkZ5v+Jg= -github.com/gogf/mysql v1.6.1-0.20210603073548-16164ae25579 h1:pP/uEy52biKDytlgK/ug8kiYPAiYu6KajKVUHfGrtyw= -github.com/gogf/mysql v1.6.1-0.20210603073548-16164ae25579/go.mod h1:52e6mXyNnHAsFrXrSnj5JPRSKsZKpHylVtA3j4AtMz8= -github.com/gomodule/redigo v2.0.0+incompatible h1:K/R+8tc58AaqLkqG2Ol3Qk+DR/TlNuhuh457pBFPtt0= -github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= +github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE= +github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/gogf/gf v1.16.6 h1:Yp5YfwnGz41d1tiVqxcWXiPXyuzjTb7ax4SnPSXxDE8= +github.com/gogf/gf v1.16.6/go.mod h1:4LoHfEBl2jbVmZpVx+qk2La3zWr1V315FtF2PVZuyQ8= +github.com/gomodule/redigo v1.8.5 h1:nRAxCa+SVsyjSBrtZmG/cqb6VbTmuRzpg/PoTFlpumc= +github.com/gomodule/redigo v1.8.5/go.mod h1:P9dn9mFrCBvWhGE1wpxx6fgq7BAeLBk+UUUzlpkBYO0= github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM= -github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grokify/html-strip-tags-go v0.0.0-20190921062105-daaa06bf1aaf h1:wIOAyJMMen0ELGiFzlmqxdcV1yGbkyHBAB6PolcNbLA= github.com/grokify/html-strip-tags-go v0.0.0-20190921062105-daaa06bf1aaf/go.mod h1:2Su6romC5/1VXOQMaWL2yb618ARB8iVo6/DR99A6d78= github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8= github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= -github.com/mattn/go-runewidth v0.0.10 h1:CoZ3S2P7pvtP45xOtBw+/mDL2z0RKI576gSkzRRpdGg= -github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rivo/uniseg v0.1.0 h1:+2KBaVoUmb9XzDsrx/Ct0W/EYOSFf/nWTauy++DprtY= -github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= go.opentelemetry.io/otel v1.0.0-RC2 h1:SHhxSjB+omnGZPgGlKe+QMp3MyazcOHdQ8qwo89oKbg= @@ -42,26 +40,23 @@ go.opentelemetry.io/otel/oteltest v1.0.0-RC2 h1:xNKqMhlZYkASSyvF4JwObZFMq0jhFN3c go.opentelemetry.io/otel/oteltest v1.0.0-RC2/go.mod h1:kiQ4tw5tAL4JLTbcOYwK1CWI1HkT5aiLzHovgOVnz/A= go.opentelemetry.io/otel/trace v1.0.0-RC2 h1:dunAP0qDULMIT82atj34m5RgvsIK6LcsXf1c/MsYg1w= go.opentelemetry.io/otel/trace v1.0.0-RC2/go.mod h1:JPQ+z6nNw9mqEGT8o3eoPTdnNI+Aj5JcxEsVGREIAy4= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20201031054903-ff519b6c9102 h1:42cLlJJdEh+ySyeUUbEQ5bsTiq8voBeTuweGVkY6Puw= -golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/net v0.0.0-20210520170846-37e1c6afe023 h1:ADo5wSpq2gqaCGQWzk7S5vd//0iyyLeAratkEoG5dLE= +golang.org/x/net v0.0.0-20210520170846-37e1c6afe023/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f h1:+Nyd8tzPX9R7BWHguqsrbFdRx3WQ/1ib8I44HXV5yTA= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.4 h1:0YWbFKbhXG/wIiuHDSKpS0Iy7FSA+u45VtBMfQcFTTc= -golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da h1:b3NXsE2LusjYGGjL5bxEVZZORm/YEFFrWFjR8eFrw/c= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/gtoken/gtoken.go b/gtoken/gtoken.go index a11f1a5..89a9a61 100644 --- a/gtoken/gtoken.go +++ b/gtoken/gtoken.go @@ -1,17 +1,18 @@ package gtoken import ( + "errors" "fmt" "github.com/gogf/gf/crypto/gaes" "github.com/gogf/gf/crypto/gmd5" "github.com/gogf/gf/encoding/gbase64" "github.com/gogf/gf/frame/g" "github.com/gogf/gf/net/ghttp" - "github.com/gogf/gf/os/glog" "github.com/gogf/gf/os/gtime" "github.com/gogf/gf/text/gstr" "github.com/gogf/gf/util/gconv" "github.com/gogf/gf/util/grand" + "net/http" "strings" ) @@ -22,6 +23,12 @@ const ( MiddlewareTypeGroup = 1 MiddlewareTypeBind = 2 MiddlewareTypeGlobal = 3 + + DefaultTimeout = 10 * 24 * 60 * 60 * 1000 + DefaultCacheKey = "GToken:" + DefaultTokenDelimiter = "_" + DefaultEncryptKey = "12345678912345678912345678912345" + DefaultAuthFailMsg = "请求错误或登录超时" ) // GfToken gtoken结构体 @@ -79,11 +86,11 @@ func (m *GfToken) InitConfig() bool { } if m.CacheKey == "" { - m.CacheKey = "GToken:" + m.CacheKey = DefaultCacheKey } if m.Timeout == 0 { - m.Timeout = 10 * 24 * 60 * 60 * 1000 + m.Timeout = DefaultTimeout } if m.MaxRefresh == 0 { @@ -91,15 +98,15 @@ func (m *GfToken) InitConfig() bool { } if m.TokenDelimiter == "" { - m.TokenDelimiter = "_" + m.TokenDelimiter = DefaultTokenDelimiter } if len(m.EncryptKey) == 0 { - m.EncryptKey = []byte("12345678912345678912345678912345") + m.EncryptKey = []byte(DefaultEncryptKey) } if m.AuthFailMsg == "" { - m.AuthFailMsg = "请求错误或登录超时" + m.AuthFailMsg = DefaultAuthFailMsg } // 设置中间件模式,未设置说明历史版本,通过GlobalMiddleware兼容 @@ -116,14 +123,14 @@ func (m *GfToken) InitConfig() bool { if !respData.Success() { err := r.Response.WriteJson(respData) if err != nil { - glog.Error(err) + g.Log().Error(err) } } else { err := r.Response.WriteJson(Succ(g.Map{ "token": respData.GetString("token"), })) if err != nil { - glog.Error(err) + g.Log().Error(err) } } } @@ -140,12 +147,12 @@ func (m *GfToken) InitConfig() bool { if respData.Success() { err := r.Response.WriteJson(Succ("Logout success")) if err != nil { - glog.Error(err) + g.Log().Error(err) } } else { err := r.Response.WriteJson(respData) if err != nil { - glog.Error(err) + g.Log().Error(err) } } } @@ -167,9 +174,9 @@ func (m *GfToken) InitConfig() bool { r.Middleware.Next() } else { var params map[string]interface{} - if r.Method == "GET" { + if r.Method == http.MethodGet { params = r.GetMap() - } else if r.Method == "POST" { + } else if r.Method == http.MethodPost { params = r.GetMap() } else { r.Response.Writeln("Request Method is ERROR! ") @@ -178,12 +185,12 @@ func (m *GfToken) InitConfig() bool { no := gconv.String(gtime.TimestampMilli()) - glog.Warning(fmt.Sprintf("[AUTH_%s][url:%s][params:%s][data:%s]", + g.Log().Warning(fmt.Sprintf("[AUTH_%s][url:%s][params:%s][data:%s]", no, r.URL.Path, params, respData.Json())) respData.Msg = m.AuthFailMsg err := r.Response.WriteJson(respData) if err != nil { - glog.Error(err) + g.Log().Error(err) } r.ExitAll() } @@ -194,24 +201,24 @@ func (m *GfToken) InitConfig() bool { } // Start 启动 -func (m *GfToken) Start() bool { +func (m *GfToken) Start() error { if !m.InitConfig() { - return false + return errors.New("InitConfig fail") } - glog.Info("[GToken][params:" + m.String() + "]start... ") + g.Log().Info("[GToken][params:" + m.String() + "]start... ") s := g.Server(m.ServerName) // 缓存模式 if m.CacheMode > CacheModeRedis { - glog.Error("[GToken]CacheMode set error") - return false + g.Log().Error("[GToken]CacheMode set error") + return errors.New("CacheMode set error") } // 认证拦截器 if m.AuthPaths == nil { - glog.Error("[GToken]HookPathList not set") - return false + g.Log().Error("[GToken]AuthPaths not set") + return errors.New("AuthPaths not set") } // 是否是全局拦截 @@ -229,25 +236,25 @@ func (m *GfToken) Start() bool { // 登录 if m.LoginPath == "" || m.LoginBeforeFunc == nil { - glog.Error("[GToken]LoginPath or LoginBeforeFunc not set") - return false + g.Log().Error("[GToken]LoginPath or LoginBeforeFunc not set") + return errors.New("LoginPath or LoginBeforeFunc not set") } s.BindHandler(m.LoginPath, m.Login) // 登出 if m.LogoutPath == "" { - glog.Error("[GToken]LogoutPath or LogoutFunc not set") - return false + g.Log().Error("[GToken]LogoutPath not set") + return errors.New("LogoutPath not set") } s.BindHandler(m.LogoutPath, m.Logout) - return true + return nil } // Stop 结束 -func (m *GfToken) Stop() bool { - glog.Info("[GToken]stop. ") - return true +func (m *GfToken) Stop() error { + g.Log().Info("[GToken]stop. ") + return nil } // GetTokenData 通过token获取对象 @@ -265,7 +272,7 @@ func (m *GfToken) GetTokenData(r *ghttp.Request) Resp { func (m *GfToken) Login(r *ghttp.Request) { userKey, data := m.LoginBeforeFunc(r) if userKey == "" { - glog.Error("[GToken]Login userKey is empty") + g.Log().Error("[GToken]Login userKey is empty") return } @@ -391,10 +398,10 @@ func (m *GfToken) getRequestToken(r *ghttp.Request) Resp { if authHeader != "" { parts := strings.SplitN(authHeader, " ", 2) if !(len(parts) == 2 && parts[0] == "Bearer") { - glog.Warning("[GToken]authHeader:" + authHeader + " get token key fail") + g.Log().Warning("[GToken]authHeader:" + authHeader + " get token key fail") return Unauthorized("get token key fail", "") } else if parts[1] == "" { - glog.Warning("[GToken]authHeader:" + authHeader + " get token fail") + g.Log().Warning("[GToken]authHeader:" + authHeader + " get token fail") return Unauthorized("get token fail", "") } @@ -453,7 +460,7 @@ func (m *GfToken) validToken(token string) Resp { } if uuid != userCacheResp.GetString("uuid") { - glog.Error("[GToken]user auth error, decryptToken:" + decryptToken.Json() + " cacheValue:" + gconv.String(userCacheResp.Data)) + g.Log().Error("[GToken]user auth error, decryptToken:" + decryptToken.Json() + " cacheValue:" + gconv.String(userCacheResp.Data)) return Unauthorized("user auth error", "") } @@ -477,7 +484,7 @@ func (m *GfToken) getToken(userKey string) Resp { if gconv.Int64(refreshTime) == 0 || nowTime > gconv.Int64(refreshTime) { userCache["createTime"] = gtime.Now().TimestampMilli() userCache["refreshTime"] = gtime.Now().TimestampMilli() + gconv.Int64(m.MaxRefresh) - glog.Debug("[GToken]refreshToken:" + gconv.String(userCache)) + g.Log().Debug("[GToken]refreshToken:" + gconv.String(userCache)) return m.setCache(cacheKey, userCache) } @@ -505,7 +512,7 @@ func (m *GfToken) EncryptToken(userKey string, uuid string) Resp { // 重新生成uuid newUuid, err := gmd5.Encrypt(grand.Letters(10)) if err != nil { - glog.Error("[GToken]uuid error", err) + g.Log().Error("[GToken]uuid error", err) return Error("uuid error") } uuid = newUuid @@ -515,7 +522,7 @@ func (m *GfToken) EncryptToken(userKey string, uuid string) Resp { token, err := gaes.Encrypt([]byte(tokenStr), m.EncryptKey) if err != nil { - glog.Error("[GToken]encrypt error token:", tokenStr, err) + g.Log().Error("[GToken]encrypt error token:", tokenStr, err) return Error("encrypt error") } @@ -534,17 +541,17 @@ func (m *GfToken) DecryptToken(token string) Resp { token64, err := gbase64.Decode([]byte(token)) if err != nil { - glog.Error("[GToken]decode error token:", token, err) + g.Log().Error("[GToken]decode error token:", token, err) return Error("decode error") } decryptToken, err2 := gaes.Decrypt(token64, m.EncryptKey) if err2 != nil { - glog.Error("[GToken]decrypt error token:", token, err2) + g.Log().Error("[GToken]decrypt error token:", token, err2) return Error("decrypt error") } tokenArray := gstr.Split(string(decryptToken), m.TokenDelimiter) if len(tokenArray) < 2 { - glog.Error("[GToken]token len error token:", token) + g.Log().Error("[GToken]token len error token:", token) return Error("token len error") } diff --git a/gtoken/gtoken_cache.go b/gtoken/gtoken_cache.go index 2aecebb..a499253 100644 --- a/gtoken/gtoken_cache.go +++ b/gtoken/gtoken_cache.go @@ -4,7 +4,6 @@ import ( "github.com/gogf/gf/encoding/gjson" "github.com/gogf/gf/frame/g" "github.com/gogf/gf/os/gcache" - "github.com/gogf/gf/os/glog" "github.com/gogf/gf/util/gconv" "time" ) @@ -17,12 +16,12 @@ func (m *GfToken) setCache(cacheKey string, userCache g.Map) Resp { case CacheModeRedis: cacheValueJson, err1 := gjson.Encode(userCache) if err1 != nil { - glog.Error("[GToken]cache json encode error", err1) + g.Log().Error("[GToken]cache json encode error", err1) return Error("cache json encode error") } _, err := g.Redis().Do("SETEX", cacheKey, m.Timeout/1000, cacheValueJson) if err != nil { - glog.Error("[GToken]cache set error", err) + g.Log().Error("[GToken]cache set error", err) return Error("cache set error") } default: @@ -39,7 +38,7 @@ func (m *GfToken) getCache(cacheKey string) Resp { case CacheModeCache: userCacheValue, err := gcache.Get(cacheKey) if err != nil { - glog.Error("[GToken]cache get error", err) + g.Log().Error("[GToken]cache get error", err) return Error("cache get error") } if userCacheValue == nil { @@ -49,7 +48,7 @@ func (m *GfToken) getCache(cacheKey string) Resp { case CacheModeRedis: userCacheJson, err := g.Redis().Do("GET", cacheKey) if err != nil { - glog.Error("[GToken]cache get error", err) + g.Log().Error("[GToken]cache get error", err) return Error("cache get error") } if userCacheJson == nil { @@ -58,7 +57,7 @@ func (m *GfToken) getCache(cacheKey string) Resp { err = gjson.DecodeTo(userCacheJson, &userCache) if err != nil { - glog.Error("[GToken]cache get json error", err) + g.Log().Error("[GToken]cache get json error", err) return Error("cache get json error") } default: @@ -74,13 +73,13 @@ func (m *GfToken) removeCache(cacheKey string) Resp { case CacheModeCache: _, err := gcache.Remove(cacheKey) if err != nil { - glog.Error(err) + g.Log().Error(err) } case CacheModeRedis: var err error _, err = g.Redis().Do("DEL", cacheKey) if err != nil { - glog.Error("[GToken]cache remove error", err) + g.Log().Error("[GToken]cache remove error", err) return Error("cache remove error") } default: diff --git a/gtoken/gtoken_group.go b/gtoken/gtoken_group.go index 5a0afab..c2dac35 100644 --- a/gtoken/gtoken_group.go +++ b/gtoken/gtoken_group.go @@ -1,38 +1,40 @@ package gtoken import ( + "errors" + "github.com/gogf/gf/frame/g" "github.com/gogf/gf/net/ghttp" - "github.com/gogf/gf/os/glog" ) // Middleware 绑定group -func (m *GfToken) Middleware(group *ghttp.RouterGroup) bool { +func (m *GfToken) Middleware(group *ghttp.RouterGroup) error { if !m.InitConfig() { - return false + return errors.New("InitConfig fail") } + // 设置为Group模式 m.MiddlewareType = MiddlewareTypeGroup - glog.Info("[GToken][params:" + m.String() + "]start... ") + g.Log().Info("[GToken][params:" + m.String() + "]start... ") // 缓存模式 if m.CacheMode > CacheModeRedis { - glog.Error("[GToken]CacheMode set error") - return false + g.Log().Error("[GToken]CacheMode set error") + return errors.New("CacheMode set error") } // 登录 if m.LoginPath == "" || m.LoginBeforeFunc == nil { - glog.Error("[GToken]LoginPath or LoginBeforeFunc not set") - return false + g.Log().Error("[GToken]LoginPath or LoginBeforeFunc not set") + return errors.New("LoginPath or LoginBeforeFunc not set") } // 登出 if m.LogoutPath == "" { - glog.Error("[GToken]LogoutPath or LogoutFunc not set") - return false + g.Log().Error("[GToken]LogoutPath not set") + return errors.New("LogoutPath not set") } group.Middleware(m.authMiddleware) group.ALL(m.LoginPath, m.Login) group.ALL(m.LogoutPath, m.Logout) - return true + return nil }