From 88861748492b5065d40c63cee60cbb7c16648ded Mon Sep 17 00:00:00 2001 From: ozlinex Date: Wed, 18 Dec 2024 10:20:45 +0800 Subject: [PATCH 1/3] chore: add warning info, clean dependency and add expired token generate test (#142) * chore: update dependency and tidy go.mod * test: token_test add generate expired token * docs: add README warning --- README.md | 2 ++ api/mw/token_test.go | 34 +++++++++++++++++++++++ docs/README.zh.md | 2 ++ go.mod | 48 +++++++++++++++----------------- go.sum | 65 +++++++++++++++----------------------------- pkg/errno/default.go | 6 ++-- 6 files changed, 85 insertions(+), 72 deletions(-) diff --git a/README.md b/README.md index a8bae895..ef2a16fd 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +> WARNING(Chinese only): 本项目受福州大学统一指导,由福州大学计算机与大数据学院、福州大学网络安全与信息化办公室管理(以上单位合称"官方")。这份源代码使用了宽松开源协议,但源码仅供学习参考,不允许该项目直接或间接性使用/修改后使用在任何非官方和 west2-online 外的应用、网站、app 及任何可以与用户产生交互的互联网信息媒介中。该警告具备行政约束效力。 +

fzuhelper-server

diff --git a/api/mw/token_test.go b/api/mw/token_test.go index 486c2aa5..ca18c285 100644 --- a/api/mw/token_test.go +++ b/api/mw/token_test.go @@ -19,13 +19,47 @@ package mw import ( "fmt" "testing" + "time" "github.com/bytedance/mockey" + "github.com/golang-jwt/jwt" "github.com/stretchr/testify/assert" "github.com/west2-online/fzuhelper-server/pkg/constants" ) +// TestCreateExpiredToken 是一个特殊测试,旨在生成一个过期的 Token +func TestCreateExpiredToken(t *testing.T) { + // 默认生成时间是一年一个月七天前的 + curTime := time.Now().AddDate(-1, -1, -7) + expiredTime := curTime.Add(constants.AccessTokenTTL) + var token string + var err error + + claims := Claims{ + Type: constants.TypeAccessToken, + StandardClaims: jwt.StandardClaims{ + ExpiresAt: expiredTime.Unix(), // 过期时间戳 + IssuedAt: curTime.Unix(), // 当前时间戳 + Issuer: constants.Issuer, // 颁发者签名 + }, + } + tokenStruct := jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims) + key, err := jwt.ParseEdPrivateKeyFromPEM([]byte(fmt.Sprintf("%v\n%v\n%v", "-----BEGIN PRIVATE KEY-----", + "此处需要修改为私钥", + "-----END PRIVATE KEY-----"))) + if err != nil { + t.Errorf("parse private key failed, err: %v", err) + } + + token, err = tokenStruct.SignedString(key) + if err != nil { + t.Errorf("sign token failed, err: %v", err) + } + + fmt.Printf("Access-Token: %s", token) +} + func TestCreateAllToken(t *testing.T) { type testCase struct { name string diff --git a/docs/README.zh.md b/docs/README.zh.md index c71118d7..bbf37fbc 100644 --- a/docs/README.zh.md +++ b/docs/README.zh.md @@ -1,3 +1,5 @@ +> 警告: 本项目受福州大学统一指导,由福州大学计算机与大数据学院、福州大学网络安全与信息化办公室管理(以上单位合称"官方")。这份源代码使用了宽松开源协议,但源码仅供学习参考,不允许该项目直接或间接性使用/修改后使用在任何非官方和 west2-online 外的应用、网站、app 及任何可以与用户产生交互的互联网信息媒介中。该警告具备行政约束效力。 +

fzuhelper-server

diff --git a/go.mod b/go.mod index 076771b5..e19262f3 100644 --- a/go.mod +++ b/go.mod @@ -7,56 +7,43 @@ replace github.com/apache/thrift => github.com/apache/thrift v0.13.0 require ( github.com/alibaba/sentinel-golang v1.0.4 github.com/apache/thrift v0.21.0 - github.com/beorn7/perks v1.0.1 // indirect github.com/bytedance/mockey v1.2.13 github.com/cloudwego/gopkg v0.1.3 - github.com/cloudwego/hertz v0.9.3 + github.com/cloudwego/hertz v0.9.4 github.com/cloudwego/kitex v0.12.0 github.com/elastic/go-elasticsearch v0.0.0 github.com/fsnotify/fsnotify v1.8.0 - github.com/go-ole/go-ole v1.3.0 // indirect - github.com/google/uuid v1.6.0 // indirect github.com/h2non/filetype v1.1.3 github.com/hertz-contrib/cors v0.1.0 github.com/hertz-contrib/gzip v0.0.3 github.com/hertz-contrib/opensergo v0.0.1 github.com/kitex-contrib/obs-opentelemetry/logging/zap v0.0.0-20241120035129-55da83caab1b github.com/kitex-contrib/registry-etcd v0.2.5 - github.com/prometheus/client_golang v1.20.5 // indirect - github.com/prometheus/client_model v0.6.1 // indirect - github.com/prometheus/common v0.61.0 // indirect - github.com/prometheus/procfs v0.15.1 // indirect github.com/redis/go-redis/v9 v9.7.0 github.com/segmentio/kafka-go v0.4.47 - github.com/shirou/gopsutil/v3 v3.24.5 // indirect github.com/spf13/viper v1.19.0 - github.com/tklauser/go-sysconf v0.3.14 // indirect - github.com/tklauser/numcpus v0.9.0 // indirect github.com/upyun/go-sdk/v3 v3.0.4 github.com/west2-online/jwch v0.2.0 - gopkg.in/yaml.v2 v2.4.0 // indirect gorm.io/driver/mysql v1.5.7 gorm.io/gorm v1.25.12 k8s.io/client-go v0.32.0 ) require ( - cloud.google.com/go v0.116.0 // indirect - cloud.google.com/go/auth v0.12.1 // indirect + cloud.google.com/go v0.117.0 // indirect + cloud.google.com/go/auth v0.13.0 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.6 // indirect cloud.google.com/go/compute/metadata v0.6.0 // indirect cloud.google.com/go/firestore v1.17.0 // indirect cloud.google.com/go/longrunning v0.6.3 // indirect filippo.io/edwards25519 v1.1.0 // indirect - github.com/andeya/ameda v1.5.3 // indirect - github.com/andeya/goutil v1.0.1 // indirect github.com/antchfx/htmlquery v1.3.3 // indirect - github.com/antchfx/xpath v1.3.2 // indirect + github.com/antchfx/xpath v1.3.3 // indirect github.com/armon/go-metrics v0.4.1 // indirect + github.com/beorn7/perks v1.0.1 // indirect github.com/bufbuild/protocompile v0.14.1 // indirect - github.com/bytedance/go-tagexpr/v2 v2.9.11 // indirect github.com/bytedance/gopkg v0.1.1 - github.com/bytedance/sonic v1.12.5 + github.com/bytedance/sonic v1.12.6 github.com/bytedance/sonic/loader v0.2.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cloudwego/base64x v0.1.4 // indirect @@ -78,6 +65,7 @@ require ( github.com/felixge/httpsnoop v1.0.4 // indirect github.com/go-logr/logr v1.4.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-ole/go-ole v1.3.0 // indirect github.com/go-resty/resty/v2 v2.16.2 // indirect github.com/go-sql-driver/mysql v1.8.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect @@ -87,6 +75,7 @@ require ( github.com/golang/protobuf v1.5.4 // indirect github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad // indirect github.com/google/s2a-go v0.1.8 // indirect + github.com/google/uuid v1.6.0 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.4 // indirect github.com/googleapis/gax-go/v2 v2.14.0 // indirect github.com/gopherjs/gopherjs v1.12.80 // indirect @@ -124,9 +113,14 @@ require ( github.com/pierrec/lz4/v4 v4.1.22 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/prometheus/client_golang v1.20.5 // indirect + github.com/prometheus/client_model v0.6.1 // indirect + github.com/prometheus/common v0.61.0 // indirect + github.com/prometheus/procfs v0.15.1 // indirect github.com/sagikazarmark/crypt v0.27.0 // indirect github.com/sagikazarmark/locafero v0.6.0 // indirect github.com/sagikazarmark/slog-shim v0.1.0 // indirect + github.com/shirou/gopsutil/v3 v3.24.5 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/smartystreets/assertions v1.2.0 // indirect github.com/smartystreets/goconvey v1.7.2 // indirect @@ -139,12 +133,13 @@ require ( github.com/tidwall/gjson v1.18.0 // indirect github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/pretty v1.2.1 // indirect + github.com/tklauser/go-sysconf v0.3.14 // indirect + github.com/tklauser/numcpus v0.9.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect go.etcd.io/etcd/api/v3 v3.5.17 // indirect go.etcd.io/etcd/client/pkg/v3 v3.5.17 // indirect go.etcd.io/etcd/client/v2 v2.305.17 // indirect go.etcd.io/etcd/client/v3 v3.5.17 // indirect - go.opencensus.io v0.24.0 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.58.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0 // indirect go.opentelemetry.io/otel v1.33.0 // indirect @@ -154,20 +149,21 @@ require ( go.uber.org/zap v1.27.0 golang.org/x/arch v0.12.0 // indirect golang.org/x/crypto v0.31.0 // indirect - golang.org/x/exp v0.0.0-20241210194714-1829a127f884 // indirect + golang.org/x/exp v0.0.0-20241215155358-4a5509556b9e // indirect golang.org/x/net v0.32.0 // indirect golang.org/x/oauth2 v0.24.0 // indirect golang.org/x/sync v0.10.0 golang.org/x/sys v0.28.0 // indirect golang.org/x/text v0.21.0 // indirect golang.org/x/time v0.8.0 - google.golang.org/api v0.211.0 // indirect - google.golang.org/genproto v0.0.0-20241209162323-e6fa225c2576 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20241209162323-e6fa225c2576 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20241209162323-e6fa225c2576 // indirect + google.golang.org/api v0.212.0 // indirect + google.golang.org/genproto v0.0.0-20241216192217-9240e9c98484 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20241216192217-9240e9c98484 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20241216192217-9240e9c98484 // indirect google.golang.org/grpc v1.69.0 // indirect - google.golang.org/protobuf v1.35.2 // indirect + google.golang.org/protobuf v1.36.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect k8s.io/apimachinery v0.32.0 // indirect k8s.io/klog/v2 v2.130.1 // indirect diff --git a/go.sum b/go.sum index 4d2b22c6..795b288d 100644 --- a/go.sum +++ b/go.sum @@ -1,9 +1,9 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.116.0 h1:B3fRrSDkLRt5qSHWe40ERJvhvnQwdZiHu0bJOpldweE= -cloud.google.com/go v0.116.0/go.mod h1:cEPSRWPzZEswwdr9BxE6ChEn01dWlTaF05LiC2Xs70U= -cloud.google.com/go/auth v0.12.1 h1:n2Bj25BUMM0nvE9D2XLTiImanwZhO3DkfWSYS/SAJP4= -cloud.google.com/go/auth v0.12.1/go.mod h1:BFMu+TNpF3DmvfBO9ClqTR/SiqVIm7LukKF9mbendF4= +cloud.google.com/go v0.117.0 h1:Z5TNFfQxj7WG2FgOGX1ekC5RiXrYgms6QscOm32M/4s= +cloud.google.com/go v0.117.0/go.mod h1:ZbwhVTb1DBGt2Iwb3tNO6SEK4q+cplHZmLWH+DelYYc= +cloud.google.com/go/auth v0.13.0 h1:8Fu8TZy167JkW8Tj3q7dIkr2v4cndv41ouecJx0PAHs= +cloud.google.com/go/auth v0.13.0/go.mod h1:COOjD9gwfKNKz+IIduatIhYJQIc0mG3H102r/EMxX6Q= cloud.google.com/go/auth/oauth2adapt v0.2.6 h1:V6a6XDu2lTwPZWOawrAa9HUK+DB2zfJyTuciBG5hFkU= cloud.google.com/go/auth/oauth2adapt v0.2.6/go.mod h1:AlmsELtlEBnaNTL7jCj8VQFLy6mbZv0s4Q7NGBeQ5E8= cloud.google.com/go/compute/metadata v0.6.0 h1:A6hENjEsCDtC1k8byVsgwvVcioamEHvZ4j01OwKxG9I= @@ -29,14 +29,11 @@ github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= github.com/alibaba/sentinel-golang v1.0.4 h1:i0wtMvNVdy7vM4DdzYrlC4r/Mpk1OKUUBurKKkWhEo8= github.com/alibaba/sentinel-golang v1.0.4/go.mod h1:Lag5rIYyJiPOylK8Kku2P+a23gdKMMqzQS7wTnjWEpk= -github.com/andeya/ameda v1.5.3 h1:SvqnhQPZwwabS8HQTRGfJwWPl2w9ZIPInHAw9aE1Wlk= -github.com/andeya/ameda v1.5.3/go.mod h1:FQDHRe1I995v6GG+8aJ7UIUToEmbdTJn/U26NCPIgXQ= -github.com/andeya/goutil v1.0.1 h1:eiYwVyAnnK0dXU5FJsNjExkJW4exUGn/xefPt3k4eXg= -github.com/andeya/goutil v1.0.1/go.mod h1:jEG5/QnnhG7yGxwFUX6Q+JGMif7sjdHmmNVjn7nhJDo= github.com/antchfx/htmlquery v1.3.3 h1:x6tVzrRhVNfECDaVxnZi1mEGrQg3mjE/rxbH2Pe6dNE= github.com/antchfx/htmlquery v1.3.3/go.mod h1:WeU3N7/rL6mb6dCwtE30dURBnBieKDC/fR8t6X+cKjU= -github.com/antchfx/xpath v1.3.2 h1:LNjzlsSjinu3bQpw9hWMY9ocB80oLOWuQqFvO6xt51U= github.com/antchfx/xpath v1.3.2/go.mod h1:i54GszH55fYfBmoZXapTHN8T8tkcHfRgLyVwwqzXNcs= +github.com/antchfx/xpath v1.3.3 h1:tmuPQa1Uye0Ym1Zn65vxPgfltWb/Lxu2jeqIGteJSRs= +github.com/antchfx/xpath v1.3.3/go.mod h1:i54GszH55fYfBmoZXapTHN8T8tkcHfRgLyVwwqzXNcs= github.com/apache/thrift v0.13.0 h1:5hryIiq9gtn+MiLVn0wP37kb/uTeRZgN08WoCsAhIhI= github.com/apache/thrift v0.13.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= @@ -61,8 +58,6 @@ github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0 github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw= github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c= github.com/bytedance/go-tagexpr/v2 v2.9.2/go.mod h1:5qsx05dYOiUXOUgnQ7w3Oz8BYs2qtM/bJokdLb79wRM= -github.com/bytedance/go-tagexpr/v2 v2.9.11 h1:jJgmoDKPKacGl0llPYbYL/+/2N+Ng0vV0ipbnVssXHY= -github.com/bytedance/go-tagexpr/v2 v2.9.11/go.mod h1:UAyKh4ZRLBPGsyTRFZoPqTni1TlojMdOJXQnEIPCX84= github.com/bytedance/gopkg v0.0.0-20220413063733-65bf48ffb3a7/go.mod h1:2ZlV9BaUH4+NXIBF0aMdKKAnHTzqH+iMU4KUjAbL23Q= github.com/bytedance/gopkg v0.0.0-20220531084716-665b4f21126f/go.mod h1:2ZlV9BaUH4+NXIBF0aMdKKAnHTzqH+iMU4KUjAbL23Q= github.com/bytedance/gopkg v0.0.0-20230728082804-614d0af6619b/go.mod h1:FtQG3YbQG9L/91pbKSw787yBQPutC+457AvDW77fgUQ= @@ -76,8 +71,8 @@ github.com/bytedance/sonic v1.3.0/go.mod h1:V973WhNhGmvHxW6nQmsHEfHaoU9F3zTF+93r github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= github.com/bytedance/sonic v1.8.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= -github.com/bytedance/sonic v1.12.5 h1:hoZxY8uW+mT+OpkcUWw4k0fDINtOcVavEsGfzwzFU/w= -github.com/bytedance/sonic v1.12.5/go.mod h1:B8Gt/XvtZ3Fqj+iSKMypzymZxw/FVwgIGKzMzT9r/rk= +github.com/bytedance/sonic v1.12.6 h1:/isNmCUF2x3Sh8RAp/4mh4ZGkcFAX/hLrzrK3AvpRzk= +github.com/bytedance/sonic v1.12.6/go.mod h1:B8Gt/XvtZ3Fqj+iSKMypzymZxw/FVwgIGKzMzT9r/rk= github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= github.com/bytedance/sonic/loader v0.2.1 h1:1GgorWTqf12TA8mma4DDSbaQigE2wOgQo7iCjjJv3+E= github.com/bytedance/sonic/loader v0.2.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= @@ -111,8 +106,8 @@ github.com/cloudwego/gopkg v0.1.3/go.mod h1:FQuXsRWRsSqJLsMVd5SYzp8/Z1y5gXKnVvRr github.com/cloudwego/hertz v0.2.1/go.mod h1:prTyExvsH/UmDkvfU3dp3EHsZFQISfT8R7BirvpTKdo= github.com/cloudwego/hertz v0.6.2/go.mod h1:2em2hGREvCBawsTQcQxyWBGVlCeo+N1pp2q0HkkbwR0= github.com/cloudwego/hertz v0.6.8/go.mod h1:KhztQcZtMQ46gOjZcmCy557AKD29cbumGEV0BzwevwA= -github.com/cloudwego/hertz v0.9.3 h1:uajvLn6LjEPjUqN/ewUZtWoRQWa2es2XTELdqDlOYMw= -github.com/cloudwego/hertz v0.9.3/go.mod h1:gGVUfJU/BOkJv/ZTzrw7FS7uy7171JeYIZvAyV3wS3o= +github.com/cloudwego/hertz v0.9.4 h1:iiZDxiN9MxQQfkjZpmT9Fl8diISgrw0QQ8j4TJF243w= +github.com/cloudwego/hertz v0.9.4/go.mod h1:UUBt8N8hSTStz7NEvLZ5mnALpBSofNL4DoYzIIp8UaY= github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= github.com/cloudwego/kitex v0.12.0 h1:TeNlAAkWc3MOIGnBQj+FcSUBan+3TBpzitnrviH0AXM= @@ -131,7 +126,6 @@ github.com/cloudwego/runtimex v0.1.1 h1:lheZjFOyKpsq8TsGGfmX9/4O7F0TKpWmB8on83k7 github.com/cloudwego/runtimex v0.1.1/go.mod h1:23vL/HGV0W8nSCHbe084AgEBdDV4rvXenEUMnUNvUd8= github.com/cloudwego/thriftgo v0.3.18 h1:gnr1vz7G3RbwwCK9AMKHZf63VYGa7ene6WbI9VrBJSw= github.com/cloudwego/thriftgo v0.3.18/go.mod h1:AdLEJJVGW/ZJYvkkYAZf5SaJH+pA3OyC801WSwqcBwI= -github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= @@ -161,9 +155,7 @@ github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaB github.com/elastic/go-elasticsearch v0.0.0 h1:Pd5fqOuBxKxv83b0+xOAJDAkziWYwFinWnBO0y+TZaA= github.com/elastic/go-elasticsearch v0.0.0/go.mod h1:TkBSJBuTyFdBnrNqoPc54FN0vKf5c04IdM4zuStJ7xg= github.com/envoyproxy/go-control-plane v0.6.9/go.mod h1:SBwIajubJHhxtWwsL9s8ss4safvEdbitLhGGK48rN6g= -github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= @@ -220,7 +212,6 @@ github.com/golang-jwt/jwt/v4 v4.5.1/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ= github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw= @@ -235,7 +226,6 @@ github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:x github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= @@ -251,8 +241,6 @@ github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5a github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= @@ -633,7 +621,6 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= -github.com/stretchr/testify v1.7.5/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= @@ -765,8 +752,8 @@ golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20241210194714-1829a127f884 h1:Y/Mj/94zIQQGHVSv1tTtQBDaQaJe62U9bkDZKKyhPCU= -golang.org/x/exp v0.0.0-20241210194714-1829a127f884/go.mod h1:qj5a5QZpwLU2NLQudwIN5koi3beDhSAlJwa67PuM98c= +golang.org/x/exp v0.0.0-20241215155358-4a5509556b9e h1:4qufH0hlUYs6AO6XmZC3GqfDPGSXHVXUFR6OND+iJX4= +golang.org/x/exp v0.0.0-20241215155358-4a5509556b9e/go.mod h1:qj5a5QZpwLU2NLQudwIN5koi3beDhSAlJwa67PuM98c= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= @@ -798,7 +785,6 @@ golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1/go.mod h1:9tjilg8BloeKEkVJvy7fQ90B1CfIiPueXVOjqfkSzI8= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= @@ -923,8 +909,8 @@ golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk= -google.golang.org/api v0.211.0 h1:IUpLjq09jxBSV1lACO33CGY3jsRcbctfGzhj+ZSE/Bg= -google.golang.org/api v0.211.0/go.mod h1:XOloB4MXFH4UTlQSGuNUxw0UT74qdENK8d6JNsXKLi0= +google.golang.org/api v0.212.0 h1:BcRj3MJfHF3FYD29rk7u9kuu1SyfGqfHcA0hSwKqkHg= +google.golang.org/api v0.212.0/go.mod h1:gICpLlpp12/E8mycRMzgy3SQ9cFh2XnVJ6vJi/kQbvI= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -933,13 +919,12 @@ google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRn google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190530194941-fb225487d101/go.mod h1:z3L6/3dTEVtUr6QSP8miRzeRqwQOioJ9I66odjN4I7s= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto v0.0.0-20241209162323-e6fa225c2576 h1:k48HcZ4FE6in0o8IflZCkc1lTc2u37nhGd8P+fo4r24= -google.golang.org/genproto v0.0.0-20241209162323-e6fa225c2576/go.mod h1:DV2u3tCn/AcVjjmGYZKt6HyvY4w4y3ipAdHkMbe/0i4= -google.golang.org/genproto/googleapis/api v0.0.0-20241209162323-e6fa225c2576 h1:CkkIfIt50+lT6NHAVoRYEyAvQGFM7xEwXUUywFvEb3Q= -google.golang.org/genproto/googleapis/api v0.0.0-20241209162323-e6fa225c2576/go.mod h1:1R3kvZ1dtP3+4p4d3G8uJ8rFk/fWlScl38vanWACI08= -google.golang.org/genproto/googleapis/rpc v0.0.0-20241209162323-e6fa225c2576 h1:8ZmaLZE4XWrtU3MyClkYqqtl6Oegr3235h7jxsDyqCY= -google.golang.org/genproto/googleapis/rpc v0.0.0-20241209162323-e6fa225c2576/go.mod h1:5uTbfoYQed2U9p3KIj2/Zzm02PYhndfdmML0qC3q3FU= +google.golang.org/genproto v0.0.0-20241216192217-9240e9c98484 h1:a/U5otbGrI6mYIO598WriFB1172i6Ktr6FGcatZD3Yw= +google.golang.org/genproto v0.0.0-20241216192217-9240e9c98484/go.mod h1:Gmd/M/W9fEyf6VSu/mWLnl+9Be51B9CLdxdsKokYq7Y= +google.golang.org/genproto/googleapis/api v0.0.0-20241216192217-9240e9c98484 h1:ChAdCYNQFDk5fYvFZMywKLIijG7TC2m1C2CMEu11G3o= +google.golang.org/genproto/googleapis/api v0.0.0-20241216192217-9240e9c98484/go.mod h1:KRUmxRI4JmbpAm8gcZM4Jsffi859fo5LQjILwuqj9z8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20241216192217-9240e9c98484 h1:Z7FRVJPSMaHQxD0uXU8WdgFh8PseLM8Q8NzhnpMrBhQ= +google.golang.org/genproto/googleapis/rpc v0.0.0-20241216192217-9240e9c98484/go.mod h1:lcTa1sDdWEIHMWlITnIczmw5w60CF9ffkb8Z+DVmmjA= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= @@ -948,10 +933,7 @@ google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ij google.golang.org/grpc v1.22.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= google.golang.org/grpc v1.69.0 h1:quSiOM1GJPmPH5XtU+BCoVXcDVJJAzNcoyfC2cCjGkI= google.golang.org/grpc v1.69.0/go.mod h1:vyjdE6jLBI76dgpDojsFGNaHlxdjXN9ghpnd2o7JGZ4= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= @@ -959,15 +941,12 @@ google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.35.2 h1:8Ar7bF+apOIoThw1EdZl0p1oWvMqTHmpA2fRTyZO8io= -google.golang.org/protobuf v1.35.2/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +google.golang.org/protobuf v1.36.0 h1:mjIs9gYtt56AzC4ZaffQuh88TZurBGhIJMBZGSxNerQ= +google.golang.org/protobuf v1.36.0/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/pkg/errno/default.go b/pkg/errno/default.go index 9648d122..b3f0c88f 100644 --- a/pkg/errno/default.go +++ b/pkg/errno/default.go @@ -24,11 +24,11 @@ var ( Success = NewErrNo(SuccessCode, "ok") CustomLaunchScreenSuccess = NewErrNo(consts.StatusOK, "ok") // 兼容处理 - AuthError = NewErrNo(AuthErrorCode, "鉴权失败") // 鉴权失败,通常是内部错误,如解析失败 - AuthInvalid = NewErrNo(AuthInvalidCode, "鉴权无效") // 鉴权无效,如令牌颁发者不是 west2-online + AuthError = NewErrNo(AuthErrorCode, "鉴权失败") // 鉴权失败,通常是内部错误,如解析失败 + AuthInvalid = NewErrNo(AuthInvalidCode, "鉴权无效") // 鉴权无效,如令牌颁发者不是 west2-online AuthAccessExpired = NewErrNo(AuthAccessExpiredCode, "访问令牌过期") // 访问令牌过期 AuthRefreshExpired = NewErrNo(AuthRefreshExpiredCode, "刷新令牌过期") // 刷新令牌过期 - AuthMissing = NewErrNo(AuthMissingCode, "鉴权缺失") // 鉴权缺失,如访问令牌缺失 + AuthMissing = NewErrNo(AuthMissingCode, "鉴权缺失") // 鉴权缺失,如访问令牌缺失 ParamError = NewErrNo(ParamErrorCode, "参数错误") // 参数校验失败,可能是参数为空、参数类型错误等 ParamMissingHeader = NewErrNo(ParamMissingHeaderCode, "缺失合法学生请求头数据") From 67125a8bf821192a7331daa782b9c503c737c456 Mon Sep 17 00:00:00 2001 From: FanR <103872180+FantasyRL@users.noreply.github.com> Date: Wed, 18 Dec 2024 21:23:31 +0800 Subject: [PATCH 2/3] fix: api.common and api.version logic error , hard-coding in tests (#144) * fix: api.common and api.version logic error * fix: hard-coding error in tests * fix: lint error * fix: ci test * fix: ci test again * fix: ci test again again * fix: ci test again again again * fix: lint * fix: CI test again --------- Co-authored-by: jiuxia211 <2064166368@qq.com> --- api/handler/api/common_service.go | 7 +- api/handler/api/paper_service_test.go | 9 +- api/handler/api/version_service.go | 28 +++--- api/handler/custom/launch_screen_service.go | 3 - api/handler/custom/url_service.go | 9 +- api/mw/token_test.go | 4 +- internal/common/service/get_agreement_test.go | 10 ++- internal/common/service/get_css_test.go | 10 ++- internal/common/service/get_html_test.go | 6 +- .../course/service/get_course_list_test.go | 87 ++++++++++--------- .../service/create_image_test.go | 3 +- .../service/delete_image_test.go | 3 +- .../service/update_image_test.go | 3 +- internal/version/service/get_setting_test.go | 7 +- .../version/service/test_get_setting_test.go | 7 +- .../version/service/upload_version_test.go | 3 +- pkg/base/pack_test.go | 6 -- 17 files changed, 109 insertions(+), 96 deletions(-) diff --git a/api/handler/api/common_service.go b/api/handler/api/common_service.go index 83df466f..8c3082bb 100644 --- a/api/handler/api/common_service.go +++ b/api/handler/api/common_service.go @@ -29,7 +29,6 @@ import ( "github.com/west2-online/fzuhelper-server/api/rpc" "github.com/west2-online/fzuhelper-server/kitex_gen/common" "github.com/west2-online/fzuhelper-server/pkg/errno" - "github.com/west2-online/fzuhelper-server/pkg/logger" ) // GetCSS . @@ -39,7 +38,6 @@ func GetCSS(ctx context.Context, c *app.RequestContext) { var req api.GetCSSRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.GetCSS: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -47,6 +45,7 @@ func GetCSS(ctx context.Context, c *app.RequestContext) { css, err := rpc.GetCSSRPC(ctx, &common.GetCSSRequest{}) if err != nil { pack.RespError(c, err) + return } c.Data(consts.StatusOK, "text/css", *css) } @@ -58,7 +57,6 @@ func GetHtml(ctx context.Context, c *app.RequestContext) { var req api.GetHtmlRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.GetHtml: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -66,6 +64,7 @@ func GetHtml(ctx context.Context, c *app.RequestContext) { html, err := rpc.GetHtmlRPC(ctx, &common.GetHtmlRequest{}) if err != nil { pack.RespError(c, err) + return } c.Data(consts.StatusOK, "text/html", *html) } @@ -77,7 +76,6 @@ func GetUserAgreement(ctx context.Context, c *app.RequestContext) { var req api.GetUserAgreementRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.GetUserAgreement: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -85,6 +83,7 @@ func GetUserAgreement(ctx context.Context, c *app.RequestContext) { userAgreement, err := rpc.GetUserAgreementRPC(ctx, &common.GetUserAgreementRequest{}) if err != nil { pack.RespError(c, err) + return } c.Data(consts.StatusOK, "text/html", *userAgreement) } diff --git a/api/handler/api/paper_service_test.go b/api/handler/api/paper_service_test.go index aad2a915..856f50ac 100644 --- a/api/handler/api/paper_service_test.go +++ b/api/handler/api/paper_service_test.go @@ -34,6 +34,7 @@ import ( "github.com/west2-online/fzuhelper-server/api/rpc" "github.com/west2-online/fzuhelper-server/kitex_gen/model" "github.com/west2-online/fzuhelper-server/kitex_gen/paper" + "github.com/west2-online/fzuhelper-server/pkg/errno" ) func TestGetDownloadUrl(t *testing.T) { @@ -60,7 +61,7 @@ func TestGetDownloadUrl(t *testing.T) { { Name: "BindAndValidateError", ExpectedError: false, - ExpectedResult: `{"code":"20001","message":"parameter error, 'filepath' field is a 'required' parameter` + + ExpectedResult: `{"code":"20001","message":"` + errno.ParamError.ErrorMsg + `, 'filepath' field is a 'required' parameter` + `, but the request body does not have this parameter 'filepath'"}`, Url: "/api/v1/paper/download", }, @@ -165,7 +166,7 @@ func TestListDirFiles(t *testing.T) { { Name: "EmptyPath", ExpectedError: false, - ExpectedResult: `{"code":"20001","message":"parameter error, path is empty"}`, + ExpectedResult: `{"code":"20001","message":"` + errno.ParamError.ErrorMsg + `, path is empty"}`, ExpectUpYunResult: nil, Path: "", }, @@ -224,7 +225,7 @@ func TestGetDownloadUrlForAndroid(t *testing.T) { { Name: "BindAndValidateError", ExpectedError: false, - ExpectedResult: `{"code":20001,"data":null,"msg":"parameter error, 'filepath' field is a 'required' parameter,` + + ExpectedResult: `{"code":20001,"data":null,"msg":"` + errno.ParamError.ErrorMsg + `, 'filepath' field is a 'required' parameter,` + ` but the request body does not have this parameter 'filepath'"}`, Url: "/api/v1/paper/download", }, @@ -329,7 +330,7 @@ func TestListDirFilesForAndroid(t *testing.T) { { Name: "EmptyPath", ExpectedError: false, - ExpectedResult: `{"code":20001,"data":null,"msg":"parameter error, path is empty"}`, + ExpectedResult: `{"code":20001,"data":null,"msg":"` + errno.ParamError.ErrorMsg + `, path is empty"}`, ExpectUpYunResult: nil, Path: "", }, diff --git a/api/handler/api/version_service.go b/api/handler/api/version_service.go index 6d88f528..cedc9c81 100644 --- a/api/handler/api/version_service.go +++ b/api/handler/api/version_service.go @@ -21,16 +21,14 @@ package api import ( "context" - "github.com/west2-online/fzuhelper-server/api/pack" - "github.com/west2-online/fzuhelper-server/api/rpc" - "github.com/west2-online/fzuhelper-server/kitex_gen/version" - "github.com/west2-online/fzuhelper-server/pkg/errno" - "github.com/west2-online/fzuhelper-server/pkg/logger" - "github.com/cloudwego/hertz/pkg/app" "github.com/cloudwego/hertz/pkg/protocol/consts" api "github.com/west2-online/fzuhelper-server/api/model/api" + "github.com/west2-online/fzuhelper-server/api/pack" + "github.com/west2-online/fzuhelper-server/api/rpc" + "github.com/west2-online/fzuhelper-server/kitex_gen/version" + "github.com/west2-online/fzuhelper-server/pkg/errno" ) // Login . @@ -40,7 +38,6 @@ func Login(ctx context.Context, c *app.RequestContext) { var req api.LoginRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.Login: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -61,7 +58,6 @@ func UploadVersion(ctx context.Context, c *app.RequestContext) { var req api.UploadRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.UploadVersion: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -91,7 +87,6 @@ func UploadParams(ctx context.Context, c *app.RequestContext) { var req api.UploadParamsRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.UploadParams: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -115,7 +110,6 @@ func DownloadReleaseApk(ctx context.Context, c *app.RequestContext) { var req api.DownloadReleaseApkRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.DownloadReleaseApk: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -123,6 +117,7 @@ func DownloadReleaseApk(ctx context.Context, c *app.RequestContext) { reUrl, err := rpc.DownloadReleaseApkRPC(ctx, &version.DownloadReleaseApkRequest{}) if err != nil { pack.RespError(c, err) + return } c.Redirect(consts.StatusFound, []byte(*reUrl)) @@ -135,7 +130,6 @@ func DownloadBetaApk(ctx context.Context, c *app.RequestContext) { var req api.DownloadBetaApkRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.DownloadBetaApk: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -143,6 +137,7 @@ func DownloadBetaApk(ctx context.Context, c *app.RequestContext) { reUrl, err := rpc.DownloadBetaApkRPC(ctx, &version.DownloadBetaApkRequest{}) if err != nil { pack.RespError(c, err) + return } c.Redirect(consts.StatusFound, []byte(*reUrl)) @@ -155,7 +150,6 @@ func GetReleaseVersion(ctx context.Context, c *app.RequestContext) { var req api.GetReleaseVersionRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.GetReleaseVersion: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -182,7 +176,6 @@ func GetBetaVersion(ctx context.Context, c *app.RequestContext) { var req api.GetBetaVersionRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.GetBetaVersion: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -209,7 +202,6 @@ func GetSetting(ctx context.Context, c *app.RequestContext) { var req api.GetSettingRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.GetSetting: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -225,6 +217,7 @@ func GetSetting(ctx context.Context, c *app.RequestContext) { }) if err != nil { pack.RespError(c, err) + return } resp.CloudSetting = rpcResp.CloudSetting @@ -238,7 +231,6 @@ func GetTest(ctx context.Context, c *app.RequestContext) { var req api.GetTestRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.GetTest: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -255,6 +247,7 @@ func GetTest(ctx context.Context, c *app.RequestContext) { }) if err != nil { pack.RespError(c, err) + return } resp.CloudSetting = rpcResp.CloudSetting @@ -268,7 +261,6 @@ func GetCloud(ctx context.Context, c *app.RequestContext) { var req api.GetCloudRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.GetCloud: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -277,6 +269,7 @@ func GetCloud(ctx context.Context, c *app.RequestContext) { rpcResp, err := rpc.GetCloudRPC(ctx, &version.GetCloudRequest{}) if err != nil { pack.RespError(c, err) + return } resp.CloudSetting = rpcResp.CloudSetting @@ -291,7 +284,6 @@ func SetCloud(ctx context.Context, c *app.RequestContext) { var req api.SetCloudRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.SetCloud: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -314,7 +306,6 @@ func GetDump(ctx context.Context, c *app.RequestContext) { var req api.GetDumpRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.GetDump: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -324,6 +315,7 @@ func GetDump(ctx context.Context, c *app.RequestContext) { rpcResp, err := rpc.GetDumpRPC(ctx, &version.GetDumpRequest{}) if err != nil { pack.RespError(c, err) + return } resp.Data = rpcResp.Data diff --git a/api/handler/custom/launch_screen_service.go b/api/handler/custom/launch_screen_service.go index 483d3d86..55d1ed52 100644 --- a/api/handler/custom/launch_screen_service.go +++ b/api/handler/custom/launch_screen_service.go @@ -26,7 +26,6 @@ import ( "github.com/west2-online/fzuhelper-server/api/rpc" "github.com/west2-online/fzuhelper-server/kitex_gen/launch_screen" "github.com/west2-online/fzuhelper-server/pkg/errno" - "github.com/west2-online/fzuhelper-server/pkg/logger" ) // MobileGetImage . @@ -36,7 +35,6 @@ func MobileGetImage(ctx context.Context, c *app.RequestContext) { var req api.MobileGetImageRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.MobileGetImage: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -65,7 +63,6 @@ func AddImagePointTime(ctx context.Context, c *app.RequestContext) { var req api.AddImagePointTimeRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.AddImagePointTime: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } diff --git a/api/handler/custom/url_service.go b/api/handler/custom/url_service.go index f637c361..12d28dbf 100644 --- a/api/handler/custom/url_service.go +++ b/api/handler/custom/url_service.go @@ -22,17 +22,15 @@ import ( "context" "net/http" - "github.com/west2-online/fzuhelper-server/kitex_gen/version" - "github.com/cloudwego/hertz/pkg/app" "github.com/cloudwego/hertz/pkg/protocol/consts" "github.com/west2-online/fzuhelper-server/api/model/api" "github.com/west2-online/fzuhelper-server/api/pack" "github.com/west2-online/fzuhelper-server/api/rpc" + "github.com/west2-online/fzuhelper-server/kitex_gen/version" "github.com/west2-online/fzuhelper-server/pkg/base" "github.com/west2-online/fzuhelper-server/pkg/errno" - "github.com/west2-online/fzuhelper-server/pkg/logger" ) var ( @@ -49,7 +47,6 @@ func APILogin(ctx context.Context, c *app.RequestContext) { var req api.LoginRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.APILogin: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -74,7 +71,6 @@ func UploadVersionInfo(ctx context.Context, c *app.RequestContext) { var req api.UploadRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.UploadVersion: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -108,7 +104,6 @@ func GetUploadParams(ctx context.Context, c *app.RequestContext) { var req api.UploadParamsRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.UploadParams: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -135,7 +130,6 @@ func GetReleaseVersionModify(ctx context.Context, c *app.RequestContext) { var req api.GetReleaseVersionRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.GetReleaseVersionModify: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } @@ -161,7 +155,6 @@ func GetBetaVersionModify(ctx context.Context, c *app.RequestContext) { var req api.GetBetaVersionRequest err = c.BindAndValidate(&req) if err != nil { - logger.Errorf("api.GetBetaVersionModify: BindAndValidate error %v", err) pack.RespError(c, errno.ParamError.WithError(err)) return } diff --git a/api/mw/token_test.go b/api/mw/token_test.go index ca18c285..a2eb9ae8 100644 --- a/api/mw/token_test.go +++ b/api/mw/token_test.go @@ -28,6 +28,8 @@ import ( "github.com/west2-online/fzuhelper-server/pkg/constants" ) +const secretKeyExample = "MC4CAQAwBQYDK2VwBCIEIPAfnWESrQOyNXXHpMqx2xcgXXvPqvuSup4YLqIjMpI3" + // TestCreateExpiredToken 是一个特殊测试,旨在生成一个过期的 Token func TestCreateExpiredToken(t *testing.T) { // 默认生成时间是一年一个月七天前的 @@ -46,7 +48,7 @@ func TestCreateExpiredToken(t *testing.T) { } tokenStruct := jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims) key, err := jwt.ParseEdPrivateKeyFromPEM([]byte(fmt.Sprintf("%v\n%v\n%v", "-----BEGIN PRIVATE KEY-----", - "此处需要修改为私钥", + secretKeyExample, "-----END PRIVATE KEY-----"))) if err != nil { t.Errorf("parse private key failed, err: %v", err) diff --git a/internal/common/service/get_agreement_test.go b/internal/common/service/get_agreement_test.go index d8ac369a..7d89c08b 100644 --- a/internal/common/service/get_agreement_test.go +++ b/internal/common/service/get_agreement_test.go @@ -18,11 +18,14 @@ package service import ( "fmt" + "strconv" + "strings" "testing" "github.com/bytedance/mockey" "github.com/stretchr/testify/assert" + "github.com/west2-online/fzuhelper-server/pkg/errno" "github.com/west2-online/fzuhelper-server/pkg/upyun" ) @@ -48,9 +51,12 @@ func TestGetUserAgreement(t *testing.T) { { name: "FileNotFound", mockFileResult: nil, - mockFileError: fmt.Errorf("file not found"), + mockFileError: errno.UpcloudError, expectedResult: nil, - expectedError: fmt.Errorf("CommonService.GetUserAgreement error:file not found"), + expectedError: fmt.Errorf("%s", strings.Join([]string{ + "CommonService.GetUserAgreement error:[", + strconv.Itoa(errno.BizFileUploadErrorCode), "] ", errno.UpcloudError.ErrorMsg, + }, "")), }, } diff --git a/internal/common/service/get_css_test.go b/internal/common/service/get_css_test.go index 2a93718c..c4ee1b82 100644 --- a/internal/common/service/get_css_test.go +++ b/internal/common/service/get_css_test.go @@ -18,11 +18,14 @@ package service import ( "fmt" + "strconv" + "strings" "testing" "github.com/bytedance/mockey" "github.com/stretchr/testify/assert" + "github.com/west2-online/fzuhelper-server/pkg/errno" "github.com/west2-online/fzuhelper-server/pkg/upyun" ) @@ -48,9 +51,12 @@ func TestGetCSS(t *testing.T) { { name: "FileNotFound", mockFileResult: nil, - mockFileError: fmt.Errorf("file not found"), + mockFileError: errno.UpcloudError, expectedResult: nil, - expectedError: fmt.Errorf("CommonService.GetCSS error:file not found"), + expectedError: fmt.Errorf("%s", strings.Join([]string{ + "CommonService.GetCSS error:[", + strconv.Itoa(errno.BizFileUploadErrorCode), "] ", errno.UpcloudError.ErrorMsg, + }, "")), }, } diff --git a/internal/common/service/get_html_test.go b/internal/common/service/get_html_test.go index c0eacfac..60541c54 100644 --- a/internal/common/service/get_html_test.go +++ b/internal/common/service/get_html_test.go @@ -18,11 +18,13 @@ package service import ( "fmt" + "strconv" "testing" "github.com/bytedance/mockey" "github.com/stretchr/testify/assert" + "github.com/west2-online/fzuhelper-server/pkg/errno" "github.com/west2-online/fzuhelper-server/pkg/upyun" ) @@ -48,9 +50,9 @@ func TestGetHtml(t *testing.T) { { name: "FileNotFound", mockFileResult: nil, - mockFileError: fmt.Errorf("file not found"), + mockFileError: errno.UpcloudError, expectedResult: nil, - expectedError: fmt.Errorf("CommonService.GetHtml error:file not found"), + expectedError: fmt.Errorf("%s", "CommonService.GetHtml error:["+strconv.Itoa(errno.BizFileUploadErrorCode)+"] "+errno.UpcloudError.ErrorMsg), }, } diff --git a/internal/course/service/get_course_list_test.go b/internal/course/service/get_course_list_test.go index 9201b724..225ee8fa 100644 --- a/internal/course/service/get_course_list_test.go +++ b/internal/course/service/get_course_list_test.go @@ -34,17 +34,6 @@ import ( ) func TestCourseService_GetCourseList(t *testing.T) { - type testCase struct { - name string - mockTerms *jwch.Term - mockCourses []*jwch.Course - mockError error - mockPutToDbError error - expectedResult []*jwch.Course - expectingError bool - expectedErrorMsg string - } - mockTerm := &jwch.Term{ Terms: []string{"202401"}, ViewState: "viewstate123", @@ -94,42 +83,62 @@ func TestCourseService_GetCourseList(t *testing.T) { }, } + type testCase struct { + name string + mockTerms *jwch.Term + mockCourses []*jwch.Course + mockPutToDbError error + expectedResult []*jwch.Course + expectingError bool + expectedErrorMsg string + mockTermsReturn *jwch.Term + mockTermsError error + mockCoursesReturn []*jwch.Course + mockCoursesError error + } + // Test cases testCases := []testCase{ { - name: "GetCourseListSuccess", - mockTerms: mockTerm, - mockCourses: mockCourses, - expectedResult: mockCourses, - expectingError: false, + name: "GetCourseListSuccess", + mockTerms: mockTerm, + mockCourses: mockCourses, + expectedResult: mockCourses, + expectingError: false, + mockTermsReturn: mockTerm, + mockCoursesReturn: mockCourses, }, { - name: "GetCourseListInvalidTerm", - mockTerms: mockTerm, - mockCourses: nil, - mockError: nil, - expectedResult: nil, - expectingError: true, - expectedErrorMsg: "Invalid term", + name: "GetCourseListInvalidTerm", + mockTerms: mockTerm, + mockCourses: nil, + expectedResult: nil, + expectingError: true, + expectedErrorMsg: "Invalid term", + mockTermsReturn: mockTerm, + mockCoursesReturn: nil, + mockCoursesError: fmt.Errorf("Invalid term"), }, { name: "GetCourseListGetTermsFailed", mockTerms: nil, mockCourses: nil, - mockError: fmt.Errorf("Get terms failed"), expectedResult: nil, expectingError: true, expectedErrorMsg: "Get terms failed", + mockTermsReturn: nil, + mockTermsError: fmt.Errorf("Get terms failed"), }, { - name: "GetCourseListGetCoursesFailed", - mockTerms: mockTerm, - mockCourses: nil, - mockError: nil, - mockPutToDbError: fmt.Errorf("put course list to db failed"), - expectedResult: nil, - expectingError: true, - expectedErrorMsg: "Get semester courses failed", + name: "GetCourseListGetCoursesFailed", + mockTerms: mockTerm, + mockCourses: nil, + expectedResult: nil, + expectingError: true, + expectedErrorMsg: "Get semester courses failed", + mockTermsReturn: mockTerm, + mockCoursesReturn: nil, + mockCoursesError: fmt.Errorf("Get semester courses failed"), }, } @@ -141,16 +150,14 @@ func TestCourseService_GetCourseList(t *testing.T) { LoginData: mockLoginData, Term: "202401", } + defer mockey.UnPatchAll() + for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - mockey.Mock((*jwch.Student).GetTerms).Return(tc.mockTerms, tc.mockError).Build() - if tc.mockCourses == nil { - mockey.Mock((*jwch.Student).GetSemesterCourses).Return(nil, fmt.Errorf("Invalid term")).Build() - } else { - mockey.Mock((*jwch.Student).GetSemesterCourses).Return(tc.mockCourses, tc.mockError).Build() - } + mockey.PatchConvey(tc.name, t, func() { + mockey.Mock((*jwch.Student).GetTerms).Return(tc.mockTermsReturn, tc.mockTermsError).Build() + mockey.Mock((*jwch.Student).GetSemesterCourses).Return(tc.mockCoursesReturn, tc.mockCoursesError).Build() mockey.Mock((*CourseService).putCourseListToDatabase).Return(tc.mockPutToDbError).Build() - defer mockey.UnPatchAll() + mockClientSet := new(base.ClientSet) mockClientSet.SFClient = new(utils.Snowflake) mockClientSet.DBClient = new(db.Database) diff --git a/internal/launch_screen/service/create_image_test.go b/internal/launch_screen/service/create_image_test.go index b296965e..b1077c75 100644 --- a/internal/launch_screen/service/create_image_test.go +++ b/internal/launch_screen/service/create_image_test.go @@ -18,6 +18,7 @@ package service import ( "context" + "strconv" "testing" "time" @@ -110,7 +111,7 @@ func TestLaunchScreenService_CreateImage(t *testing.T) { if tc.expectingError { assert.Nil(t, result) - assert.EqualError(t, err, "LaunchScreenService.CreateImage error:[40006] upload to upcloud error") + assert.EqualError(t, err, "LaunchScreenService.CreateImage error:["+strconv.Itoa(errno.BizFileUploadErrorCode)+"] "+errno.UpcloudError.ErrorMsg) } else { assert.NoError(t, err) assert.Equal(t, tc.expectedResult, result) diff --git a/internal/launch_screen/service/delete_image_test.go b/internal/launch_screen/service/delete_image_test.go index 49da07e0..4704096e 100644 --- a/internal/launch_screen/service/delete_image_test.go +++ b/internal/launch_screen/service/delete_image_test.go @@ -18,6 +18,7 @@ package service import ( "context" + "strconv" "testing" "time" @@ -94,7 +95,7 @@ func TestLaunchScreenService_DeleteImage(t *testing.T) { err := launchScreenService.DeleteImage(req.PictureId) if tc.expectingError { - assert.EqualError(t, err, "LaunchScreen.DeleteImage error: [40006] upload to upcloud error") + assert.EqualError(t, err, "LaunchScreen.DeleteImage error: ["+strconv.Itoa(errno.BizFileUploadErrorCode)+"] "+errno.UpcloudError.ErrorMsg) } else { assert.NoError(t, err) } diff --git a/internal/launch_screen/service/update_image_test.go b/internal/launch_screen/service/update_image_test.go index 46b1e95d..72e33082 100644 --- a/internal/launch_screen/service/update_image_test.go +++ b/internal/launch_screen/service/update_image_test.go @@ -18,6 +18,7 @@ package service import ( "context" + "strconv" "testing" "time" @@ -136,7 +137,7 @@ func TestLaunchScreenService_UpdateImagePath(t *testing.T) { if !tc.mockIsExist { assert.EqualError(t, err, "LaunchScreenService.UpdateImagePath db.GetImageById error: record not found") } else { - assert.EqualError(t, err, "LaunchScreenService.UpdateImagePath error: [40006] upload to upcloud error") + assert.EqualError(t, err, "LaunchScreenService.UpdateImagePath error: ["+strconv.Itoa(errno.BizFileUploadErrorCode)+"] "+errno.UpcloudError.ErrorMsg) } } else { assert.NoError(t, err) diff --git a/internal/version/service/get_setting_test.go b/internal/version/service/get_setting_test.go index bef8083d..6ceaab2e 100644 --- a/internal/version/service/get_setting_test.go +++ b/internal/version/service/get_setting_test.go @@ -19,6 +19,8 @@ package service import ( "encoding/json" "fmt" + "strconv" + "strings" "testing" "github.com/bytedance/mockey" @@ -77,7 +79,10 @@ func TestGetCloudSetting(t *testing.T) { mockCriteria: &pack.Plan{Name: strPtr("Non-Matching Plan")}, mockPlanList: []pack.Plan{{Name: strPtr("Other Plan"), Plan: json.RawMessage(mockPlanResult)}}, expectedResult: nil, - expectedError: fmt.Errorf("VersionService.GetCloudSetting error:[40001] no matching plan"), + expectedError: fmt.Errorf("%s", strings.Join([]string{ + "VersionService.GetCloudSetting error:[", + strconv.Itoa(int(errno.NoMatchingPlanError.ErrorCode)), "] ", errno.NoMatchingPlanError.ErrorMsg, + }, "")), }, } diff --git a/internal/version/service/test_get_setting_test.go b/internal/version/service/test_get_setting_test.go index 6cda800b..44681892 100644 --- a/internal/version/service/test_get_setting_test.go +++ b/internal/version/service/test_get_setting_test.go @@ -19,6 +19,8 @@ package service import ( "encoding/json" "fmt" + "strconv" + "strings" "testing" "github.com/bytedance/mockey" @@ -67,7 +69,10 @@ func TestTestSetting(t *testing.T) { mockCriteria: &pack.Plan{Name: strPtr("Non-Matching Plan")}, mockPlanList: []pack.Plan{{Name: strPtr("Other Plan"), Plan: json.RawMessage(mockPlanResult)}}, expectedResult: nil, - expectedError: fmt.Errorf("VersionService.TestSetting error:[40001] no matching plan"), + expectedError: fmt.Errorf("%s", strings.Join([]string{ + "VersionService.TestSetting error:[", + strconv.Itoa(int(errno.NoMatchingPlanError.ErrorCode)), "] ", errno.NoMatchingPlanError.ErrorMsg, + }, "")), }, } diff --git a/internal/version/service/upload_version_test.go b/internal/version/service/upload_version_test.go index f89b55e2..6fb52886 100644 --- a/internal/version/service/upload_version_test.go +++ b/internal/version/service/upload_version_test.go @@ -23,6 +23,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/west2-online/fzuhelper-server/kitex_gen/version" + "github.com/west2-online/fzuhelper-server/pkg/errno" "github.com/west2-online/fzuhelper-server/pkg/upyun" "github.com/west2-online/fzuhelper-server/pkg/utils" ) @@ -100,7 +101,7 @@ func TestUploadVersion(t *testing.T) { Type: "invalidType", }, expectedError: true, - expectedErrorInfo: "parameter error", + expectedErrorInfo: errno.ParamError.ErrorMsg, }, } diff --git a/pkg/base/pack_test.go b/pkg/base/pack_test.go index 085298d0..5862098b 100644 --- a/pkg/base/pack_test.go +++ b/pkg/base/pack_test.go @@ -45,12 +45,6 @@ func TestBuildSuccessResp(t *testing.T) { assert.Equal(t, errno.Success.ErrorMsg, r.Msg) } -func TestLogError(t *testing.T) { - LogError(nil) - LogError(fmt.Errorf("ok")) - LogError(errno.Success) -} - func TestBuildRespAndLog(t *testing.T) { nilError := BuildBaseResp(nil) assert.Equal(t, int64(errno.SuccessCode), nilError.Code) From f4c486477cbdaaab4c771e6f1b1cd107769624c0 Mon Sep 17 00:00:00 2001 From: mutezebra Date: Fri, 20 Dec 2024 12:52:11 +0800 Subject: [PATCH 3/3] feat: output log to file and update them periodically (#145) --- config/config.go | 13 +-- go.mod | 7 +- go.sum | 8 +- pkg/base/client/db.go | 2 +- pkg/base/pack_test.go | 58 ++++++---- pkg/constants/log.go | 20 +--- pkg/eshook/logger.go | 5 +- pkg/logger/config.go | 79 +++++--------- pkg/logger/klog.go | 120 +++++++++++++++++++++ pkg/logger/logger.go | 221 ++++++++++++++++++++++++++++---------- pkg/logger/logger_test.go | 126 ++++++++++++++++++++++ pkg/logger/mysql.go | 27 +++++ pkg/logger/out_test.go | 42 ++++++++ pkg/logger/output.go | 57 +++++++--- pkg/logger/redis.go | 10 +- 15 files changed, 602 insertions(+), 193 deletions(-) create mode 100644 pkg/logger/klog.go create mode 100644 pkg/logger/logger_test.go create mode 100644 pkg/logger/mysql.go create mode 100644 pkg/logger/out_test.go diff --git a/config/config.go b/config/config.go index 7854c047..18c7dc7e 100644 --- a/config/config.go +++ b/config/config.go @@ -119,15 +119,10 @@ func getService(name string) *service { } } -// GetLoggerLevel 会尝试对文本日志等级做转换,如果失败则返回默认 INFO -func GetLoggerLevel() int64 { +// GetLoggerLevel 会返回服务的日志等级 +func GetLoggerLevel() string { if Server == nil { - return constants.LevelInfo // 默认 INFO + return constants.DefaultLogLevel } - - v, ok := constants.LevelMap[Server.LogLevel] - if !ok { - return constants.LevelInfo // 默认 INFO - } - return v + return Server.LogLevel } diff --git a/go.mod b/go.mod index e19262f3..bc9abb77 100644 --- a/go.mod +++ b/go.mod @@ -17,7 +17,6 @@ require ( github.com/hertz-contrib/cors v0.1.0 github.com/hertz-contrib/gzip v0.0.3 github.com/hertz-contrib/opensergo v0.0.1 - github.com/kitex-contrib/obs-opentelemetry/logging/zap v0.0.0-20241120035129-55da83caab1b github.com/kitex-contrib/registry-etcd v0.2.5 github.com/redis/go-redis/v9 v9.7.0 github.com/segmentio/kafka-go v0.4.47 @@ -42,7 +41,7 @@ require ( github.com/armon/go-metrics v0.4.1 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bufbuild/protocompile v0.14.1 // indirect - github.com/bytedance/gopkg v0.1.1 + github.com/bytedance/gopkg v0.1.1 // indirect github.com/bytedance/sonic v1.12.6 github.com/bytedance/sonic/loader v0.2.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect @@ -123,7 +122,7 @@ require ( github.com/shirou/gopsutil/v3 v3.24.5 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/smartystreets/assertions v1.2.0 // indirect - github.com/smartystreets/goconvey v1.7.2 // indirect + github.com/smartystreets/goconvey v1.7.2 github.com/sourcegraph/conc v0.3.0 // indirect github.com/spf13/afero v1.11.0 // indirect github.com/spf13/cast v1.7.0 // indirect @@ -150,7 +149,7 @@ require ( golang.org/x/arch v0.12.0 // indirect golang.org/x/crypto v0.31.0 // indirect golang.org/x/exp v0.0.0-20241215155358-4a5509556b9e // indirect - golang.org/x/net v0.32.0 // indirect + golang.org/x/net v0.33.0 // indirect golang.org/x/oauth2 v0.24.0 // indirect golang.org/x/sync v0.10.0 golang.org/x/sys v0.28.0 // indirect diff --git a/go.sum b/go.sum index 795b288d..7e40c323 100644 --- a/go.sum +++ b/go.sum @@ -377,8 +377,6 @@ github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8 github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/kitex-contrib/obs-opentelemetry/logging/zap v0.0.0-20241120035129-55da83caab1b h1:td+0YgPBJkuA8srZwO7SjqYqNSW0fEdGDaCEWAmzQGA= -github.com/kitex-contrib/obs-opentelemetry/logging/zap v0.0.0-20241120035129-55da83caab1b/go.mod h1:NUuhhOLwpinYkidyb6X+e8LS+ccZO4NL95QfTjg0//E= github.com/kitex-contrib/registry-etcd v0.2.5 h1:16On5GQAmN9tdbFy95QtwGH3aTWnW/BfdvdDmzLIytE= github.com/kitex-contrib/registry-etcd v0.2.5/go.mod h1:Imgvy+EkqExHuJs4+VFK0g1bFWHaCJ0KuK1sofWYZf4= github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU= @@ -706,8 +704,6 @@ go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.20.0 h1:DeFD0VgTZ+Cj6hxravY go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.20.0/go.mod h1:GijYcYmNpX1KazD5JmWGsi4P7dDTTTnfv1UbGn84MnU= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.20.0 h1:gvmNvqrPYovvyRmCSygkUDyL8lC5Tl845MLEwqpxhEU= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.20.0/go.mod h1:vNUq47TGFioo+ffTSnKNdob241vePmtNZnAODKapKd0= -go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.16.0 h1:+XWJd3jf75RXJq29mxbuXhCXFDG3S3R4vBUeSI2P7tE= -go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.16.0/go.mod h1:hqgzBPTf4yONMFgdZvL/bK42R/iinTyVQtiWihs3SZc= go.opentelemetry.io/otel/metric v1.33.0 h1:r+JOocAyeRVXD8lZpjdQjzMadVZp2M4WmQ+5WtEnklQ= go.opentelemetry.io/otel/metric v1.33.0/go.mod h1:L9+Fyctbp6HFTddIxClbQkjtubW6O9QS3Ann/M82u6M= go.opentelemetry.io/otel/sdk v1.31.0 h1:xLY3abVHYZ5HSfOg3l2E5LUj2Cwva5Y7yGxnSW9H5Gk= @@ -793,8 +789,8 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= -golang.org/x/net v0.32.0 h1:ZqPmj8Kzc+Y6e0+skZsuACbx+wzMgo5MQsJh9Qd6aYI= -golang.org/x/net v0.32.0/go.mod h1:CwU0IoeOlnQQWJ6ioyFrfRuomB8GKF6KbYXZVyeXNfs= +golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= +golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.24.0 h1:KTBBxWqUa0ykRPLtV69rRto9TLXcqYkeswu48x/gvNE= diff --git a/pkg/base/client/db.go b/pkg/base/client/db.go index f8d8e0c5..5309e8b2 100644 --- a/pkg/base/client/db.go +++ b/pkg/base/client/db.go @@ -46,7 +46,7 @@ func InitMySQL(tableName string) (db *gorm.DB, err error) { SingularTable: true, // 使用单数表名 }, Logger: glogger.New( - logger.GetLogger(), + logger.GetMysqlLogger(), glogger.Config{ SlowThreshold: time.Second, // 超过一秒的查询被认为是慢查询 LogLevel: glogger.Warn, // 日志等级 diff --git a/pkg/base/pack_test.go b/pkg/base/pack_test.go index 5862098b..f030273c 100644 --- a/pkg/base/pack_test.go +++ b/pkg/base/pack_test.go @@ -20,41 +20,55 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" + . "github.com/smartystreets/goconvey/convey" "github.com/west2-online/fzuhelper-server/pkg/errno" ) func TestBuildBaseResp(t *testing.T) { - nilError := BuildBaseResp(nil) - assert.Equal(t, int64(errno.SuccessCode), nilError.Code) - assert.Equal(t, errno.Success.ErrorMsg, nilError.Msg) + Convey("TestBuildBaseResp", t, func() { + nilError := BuildBaseResp(nil) + So(nilError.Code, ShouldEqual, int64(errno.SuccessCode)) + So(nilError.Code, ShouldEqual, int64(errno.SuccessCode)) + So(nilError.Msg, ShouldEqual, errno.Success.ErrorMsg) - normalError := BuildBaseResp(fmt.Errorf("ok")) - assert.Equal(t, int64(errno.InternalServiceErrorCode), normalError.Code) - assert.Equal(t, "ok", normalError.Msg) + normalError := BuildBaseResp(fmt.Errorf("ok")) + So(normalError.Code, ShouldEqual, int64(errno.InternalServiceErrorCode)) + So(normalError.Msg, ShouldEqual, "ok") - errnoError := BuildBaseResp(errno.NewErrNo(200, "ok")) - assert.Equal(t, int64(200), errnoError.Code) - assert.Equal(t, "ok", errnoError.Msg) + errnoError := BuildBaseResp(errno.NewErrNo(200, "ok")) + So(errnoError.Code, ShouldEqual, int64(200)) + So(errnoError.Msg, ShouldEqual, "ok") + }) } func TestBuildSuccessResp(t *testing.T) { - r := BuildSuccessResp() - assert.Equal(t, int64(errno.SuccessCode), r.Code) - assert.Equal(t, errno.Success.ErrorMsg, r.Msg) + Convey("TestBuildSuccessResp", t, func() { + r := BuildSuccessResp() + So(r.Code, ShouldEqual, int64(errno.SuccessCode)) + So(r.Msg, ShouldEqual, errno.Success.ErrorMsg) + }) +} + +func TestLogError(t *testing.T) { + LogError(nil) + LogError(fmt.Errorf("ok")) + LogError(errno.Success) + // LogError(errno.NewErrNoWithStack(200, "ok")) // have tested } func TestBuildRespAndLog(t *testing.T) { - nilError := BuildBaseResp(nil) - assert.Equal(t, int64(errno.SuccessCode), nilError.Code) - assert.Equal(t, errno.Success.ErrorMsg, nilError.Msg) + Convey("Test BuildRespAndLog", t, func() { + nilError := BuildBaseResp(nil) + So(nilError.Code, ShouldEqual, int64(errno.SuccessCode)) + So(nilError.Msg, ShouldEqual, errno.Success.ErrorMsg) - normalError := BuildBaseResp(fmt.Errorf("ok")) - assert.Equal(t, int64(errno.InternalServiceErrorCode), normalError.Code) - assert.Equal(t, "ok", normalError.Msg) + normalError := BuildBaseResp(fmt.Errorf("ok")) + So(normalError.Code, ShouldEqual, int64(errno.InternalServiceErrorCode)) + So("ok", ShouldEqual, normalError.Msg) - errnoError := BuildBaseResp(errno.NewErrNo(200, "ok")) - assert.Equal(t, int64(200), errnoError.Code) - assert.Equal(t, "ok", errnoError.Msg) + errnoError := BuildBaseResp(errno.NewErrNo(200, "ok")) + So(errnoError.Code, ShouldEqual, int64(200)) + So(errnoError.Msg, ShouldEqual, "ok") + }) } diff --git a/pkg/constants/log.go b/pkg/constants/log.go index 1f2ec35c..cb6ded3b 100644 --- a/pkg/constants/log.go +++ b/pkg/constants/log.go @@ -20,22 +20,6 @@ const ( // LogFilePath 对应 ${pwd}/{LogFilePath}/log.log 相对于当前运行路径而言 LogFilePath = "log" - LevelTrace int64 = iota - LevelDebug - LevelInfo - LevelNotice - LevelWarn - LevelError - LevelFatal + // DefaultLogLevel 是默认的日志等级. Supported Level: debug info warn error fatal + DefaultLogLevel = "INFO" ) - -// LevelMap 适用于读取配置后进行日志转换 -var LevelMap = map[string]int64{ - "TRACE": LevelTrace, - "DEBUG": LevelDebug, - "INFO": LevelInfo, - "NOTICE": LevelNotice, - "WARN": LevelWarn, - "ERROR": LevelError, - "FATAL": LevelFatal, -} diff --git a/pkg/eshook/logger.go b/pkg/eshook/logger.go index eedf97a3..a07b2923 100644 --- a/pkg/eshook/logger.go +++ b/pkg/eshook/logger.go @@ -17,9 +17,7 @@ limitations under the License. package eshook import ( - "github.com/cloudwego/kitex/pkg/klog" elastic "github.com/elastic/go-elasticsearch" - "go.uber.org/zap" "github.com/west2-online/fzuhelper-server/config" "github.com/west2-online/fzuhelper-server/pkg/base/client" @@ -39,6 +37,5 @@ func InitLoggerWithHook(index string, esclient *elastic.Client) { } hook := NewElasticHook(esclient, config.Elasticsearch.Host, index) - v := logger.DefaultLogger(zap.Hooks(hook.Fire)) - klog.SetLogger(v) + logger.AddLoggerHook(hook.Fire) } diff --git a/pkg/logger/config.go b/pkg/logger/config.go index a248e7bb..d38b41ee 100644 --- a/pkg/logger/config.go +++ b/pkg/logger/config.go @@ -19,66 +19,47 @@ package logger import ( "os" - "github.com/cloudwego/kitex/pkg/klog" - kitexzap "github.com/kitex-contrib/obs-opentelemetry/logging/zap" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) -const ( - DefaultSkip = 4 // 默认跳过的栈帧数 -) - -type Config struct { - Enc zapcore.Encoder - Ws zapcore.WriteSyncer - lvl zapcore.Level +type config struct { + core zapcore.Core + enc zapcore.Encoder + ws zapcore.WriteSyncer + lvl zapcore.Level } -func InitLoggerWithLevel(lvl zapcore.Level) { - klog.SetLogger(NewLogger(lvl, Config{})) -} +func buildConfig(core zapcore.Core) *config { + cfg := defaultConfig() + cfg.core = core + if cfg.core == nil { + cfg.core = zapcore.NewCore(cfg.enc, cfg.ws, cfg.lvl) + } -func InitLoggerWithConfig(lvl zapcore.Level, cfg Config, options ...zap.Option) { - klog.SetLogger(NewLogger(lvl, cfg, options...)) + return cfg } -func NewLogger(lvl zapcore.Level, cfg Config, options ...zap.Option) *kitexzap.Logger { - if cfg.Enc == nil { - cfg.Enc = defaultEnc() - } - if cfg.Ws == nil { - cfg.Ws = defaultWs() - } - cfg.lvl = lvl - - var ops []kitexzap.Option - ops = append(ops, kitexzap.WithZapOptions(defaultOptions()...)) - ops = append(ops, kitexzap.WithCoreEnc(cfg.Enc)) - ops = append(ops, kitexzap.WithCoreWs(cfg.Ws)) - ops = append(ops, kitexzap.WithCoreLevel(zap.NewAtomicLevelAt(cfg.lvl))) - ops = append(ops, kitexzap.WithZapOptions(options...)) - return kitexzap.NewLogger(ops...) +func BuildLogger(cfg *config, opts ...zap.Option) *zap.Logger { + return zap.New(cfg.core, opts...) } -func DefaultLogger(options ...zap.Option) *kitexzap.Logger { - var ops []kitexzap.Option - ops = append(ops, kitexzap.WithZapOptions(defaultOptions()...)) - ops = append(ops, kitexzap.WithCoreEnc(defaultEnc())) - ops = append(ops, kitexzap.WithCoreWs(defaultWs())) - ops = append(ops, kitexzap.WithCoreLevel(zap.NewAtomicLevelAt(defaultLvl()))) - ops = append(ops, kitexzap.WithZapOptions(options...)) - return kitexzap.NewLogger(ops...) +func defaultConfig() *config { + return &config{ + enc: defaultEnc(), + ws: defaultWs(), + lvl: defaultLvl(), + } } func defaultEnc() zapcore.Encoder { cfg := zapcore.EncoderConfig{ - TimeKey: "time", - LevelKey: "level", - NameKey: "logger", - CallerKey: "caller", - MessageKey: "msg", - StacktraceKey: "stacktrace", + TimeKey: "time", + LevelKey: "level", + NameKey: "logger", + CallerKey: "caller", + MessageKey: "msg", + // StacktraceKey: "stacktrace", LineEnding: zapcore.DefaultLineEnding, EncodeLevel: zapcore.CapitalLevelEncoder, // 日志等级大写 EncodeTime: zapcore.ISO8601TimeEncoder, // 时间格式 @@ -96,11 +77,3 @@ func defaultWs() zapcore.WriteSyncer { func defaultLvl() zapcore.Level { return zapcore.DebugLevel } - -func defaultOptions() []zap.Option { - return []zap.Option{ - zap.AddStacktrace(zap.ErrorLevel), - zap.AddCaller(), - zap.AddCallerSkip(DefaultSkip), - } -} diff --git a/pkg/logger/klog.go b/pkg/logger/klog.go new file mode 100644 index 00000000..13792582 --- /dev/null +++ b/pkg/logger/klog.go @@ -0,0 +1,120 @@ +/* +Copyright 2024 The west2-online Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package logger + +import ( + "context" + "io" + + "github.com/cloudwego/kitex/pkg/klog" +) + +type KlogLogger struct{} + +func GetKlogLogger() *KlogLogger { + return &KlogLogger{} +} + +func (l *KlogLogger) Trace(v ...interface{}) { + Debug(v...) +} + +func (l *KlogLogger) Debug(v ...interface{}) { + Debug(v...) +} + +func (l *KlogLogger) Info(v ...interface{}) { + Info(v...) +} + +func (l *KlogLogger) Notice(v ...interface{}) { + Info(v...) +} + +func (l *KlogLogger) Warn(v ...interface{}) { + Warn(v...) +} + +func (l *KlogLogger) Error(v ...interface{}) { + Error(v...) +} + +func (l *KlogLogger) Fatal(v ...interface{}) { + Fatal(v...) +} + +func (l *KlogLogger) Tracef(format string, v ...interface{}) { + Debugf(format, v...) +} + +func (l *KlogLogger) Debugf(format string, v ...interface{}) { + Debugf(format, v...) +} + +func (l *KlogLogger) Infof(format string, v ...interface{}) { + Infof(format, v...) +} + +func (l *KlogLogger) Noticef(format string, v ...interface{}) { + Infof(format, v...) +} + +func (l *KlogLogger) Warnf(format string, v ...interface{}) { + Warnf(format, v...) +} + +func (l *KlogLogger) Errorf(format string, v ...interface{}) { + Errorf(format, v...) +} + +func (l *KlogLogger) Fatalf(format string, v ...interface{}) { + Fatalf(format, v...) +} + +func (l *KlogLogger) CtxTracef(ctx context.Context, format string, v ...interface{}) { + Debugf(format, v...) +} + +func (l *KlogLogger) CtxDebugf(ctx context.Context, format string, v ...interface{}) { + Debugf(format, v...) +} + +func (l *KlogLogger) CtxInfof(ctx context.Context, format string, v ...interface{}) { + Infof(format, v...) +} + +func (l *KlogLogger) CtxNoticef(ctx context.Context, format string, v ...interface{}) { + Infof(format, v...) +} + +func (l *KlogLogger) CtxWarnf(ctx context.Context, format string, v ...interface{}) { + Warnf(format, v...) +} + +func (l *KlogLogger) CtxErrorf(ctx context.Context, format string, v ...interface{}) { + Errorf(format, v...) +} + +func (l *KlogLogger) CtxFatalf(ctx context.Context, format string, v ...interface{}) { + Fatalf(format, v...) +} + +func (l *KlogLogger) SetLevel(klog.Level) { +} + +func (l *KlogLogger) SetOutput(io.Writer) { +} diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go index c719d45e..318d401f 100644 --- a/pkg/logger/logger.go +++ b/pkg/logger/logger.go @@ -19,33 +19,81 @@ package logger import ( "fmt" "os" - "path/filepath" - "runtime" "strings" + "sync" + "sync/atomic" + "time" - "github.com/bytedance/gopkg/util/logger" "github.com/cloudwego/kitex/pkg/klog" - kitexzap "github.com/kitex-contrib/obs-opentelemetry/logging/zap" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" "github.com/west2-online/fzuhelper-server/pkg/constants" ) +type controlLogger struct { + mu sync.RWMutex + logger *logger + hooks []func(zapcore.Entry) error + done atomic.Bool +} + +type logger struct { + *zap.SugaredLogger +} + var ( - loggerObj *kitexzap.Logger - stdErrFileHandler *os.File // 全局变量,避免被 GC 回收 - logFileHandler *os.File + control controlLogger + logLevel = zapcore.InfoLevel + callerSkip = 2 + logFileHandler atomic.Value + stdErrFileHandler atomic.Value // 全局变量,避免被 GC 回收 ) -type Logger struct { - *kitexzap.Logger +// init mainly used to output logs before logger.Init +func init() { + cfg := buildConfig(nil) + control.logger = &logger{BuildLogger(cfg, control.addZapOptions()...).Sugar()} + control.hooks = make([]func(zapcore.Entry) error, 0) + + klog.SetLogger(GetKlogLogger()) } -const ( - permission = 0o755 // 用户具有读/写/执行权限,组用户和其它用户具有读写权限 -) +func Init(service string, level string) { + if service == "" { + panic("server should not be empty") + } + + logLevel = parseLevel(level) + control.updateLogger(service) + control.scheduleUpdateLogger(service) +} + +// AddLoggerHook 会将传进的参数在每一次日志输出后执行 +func AddLoggerHook(fns ...func(zapcore.Entry) error) { + control.hooks = append(control.hooks, fns...) +} -// Init 将会依据服务名在日志目录(参考 constants 设置的常量)下构建相应的标准输出和日志输出 -func Init(service string, level int64) { +func (l *controlLogger) scheduleUpdateLogger(service string) { + // 确保只开启一次定时更新 + if !l.done.Load() { + l.done.Store(true) + go func() { + for { + now := time.Now() + //nolint + next := now.Truncate(24 * time.Hour).Add(24 * time.Hour) + time.Sleep(time.Until(next)) + l.updateLogger(service) + } + }() + } +} + +func (l *controlLogger) updateLogger(service string) { + // 避免 logger 更新时引发竞态 + l.mu.Lock() + defer l.mu.Unlock() var err error var pwd string @@ -54,62 +102,123 @@ func Init(service string, level int64) { panic(err) } - logPath := fmt.Sprintf("%s/%s/%s.log", pwd, constants.LogFilePath, service) - stderrPath := fmt.Sprintf("%s/%s/%s_stderr.log", pwd, constants.LogFilePath, service) + // 设置文件输出的位置 + date := time.Now().Format("2006-01-02") + logPath := fmt.Sprintf("%s/%s/%s/%s.log", pwd, constants.LogFilePath, date, service) + stderrPath := fmt.Sprintf("%s/%s/%s/%s_stderr.log", pwd, constants.LogFilePath, date, service) + + // 打开文件,并设置无引用时关闭文件 + logFileHandler.Store(checkAndOpenFile(logPath)) + stdErrFileHandler.Store(checkAndOpenFile(stderrPath)) - logFileHandler = checkAndOpenFile(logPath) - stdErrFileHandler = checkAndOpenFile(stderrPath) + // 让日志输出到不同的位置 + logLevelFn := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool { + return lvl <= logLevel + }) + errLevelFn := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool { + return lvl > logLevel + }) + + logCore := zapcore.NewCore(defaultEnc(), zapcore.Lock(logFileHandler.Load().(*os.File)), logLevelFn) //nolint + errCore := zapcore.NewCore(defaultEnc(), zapcore.Lock(stdErrFileHandler.Load().(*os.File)), errLevelFn) //nolint - // 这个系统调用在某些场合(含 tmux 或者跨平台)上并不好用,还是用 golang 内置的好 - // if err = syscall.Dup2(int(stdErrFileHandler.Fd()), int(os.Stderr.Fd())); err != nil { - // panic(fmt.Sprintf("dup2 stderr failed: %v", err)) - // } - os.Stderr = stdErrFileHandler // 直接替换标准错误输出,需要注意的是,这里不替换 os.Stdout + cfg := buildConfig(zapcore.NewTee(logCore, errCore)) - loggerObj = DefaultLogger() - klog.SetLogger(loggerObj) - klog.SetOutput(logFileHandler) - klog.SetLevel(klog.Level(level)) - logger.Infof("logger init success, log level: %d", level) + l.logger.SugaredLogger = BuildLogger(cfg, l.addZapOptions()...).Sugar() } -// getCurrentDirectory 会返回当前运行的目录 -func getCurrentDirectory() (string, error) { - dir, err := filepath.Abs(filepath.Dir(os.Args[0])) - if err != nil { - return "", err +func (l *controlLogger) addZapOptions() []zap.Option { + var opts []zap.Option + if len(l.hooks) != 0 { + opts = append(opts, zap.Hooks(l.hooks...)) } + opts = append(opts, zap.AddCaller()) + opts = append(opts, zap.AddCallerSkip(callerSkip)) + return opts +} - return strings.ReplaceAll(dir, "\\", "/"), nil +func (l *controlLogger) debug(args ...interface{}) { + l.mu.RLock() // 锁的是 logger 的操作权限, 而不是写操作, 写操作在 zap.logger 的内部有锁. + defer l.mu.RUnlock() + l.logger.Debug(args...) } -func checkAndOpenFile(path string) *os.File { - var err error - var handler *os.File - if err = os.MkdirAll(filepath.Dir(path), permission); err != nil { - panic(err) - } +func (l *controlLogger) debugf(template string, args ...interface{}) { + l.mu.RLock() + defer l.mu.RUnlock() + l.logger.Debugf(template, args...) +} - handler, err = os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, permission) - if err != nil { - panic(err) - } - runtime.SetFinalizer(handler, func(fd *os.File) { - if err := fd.Close(); err != nil { - logger.Infof(fmt.Sprintf("close file failed %v", err)) - } - }) - return handler +func (l *controlLogger) info(args ...interface{}) { + l.mu.RLock() + defer l.mu.RUnlock() + l.logger.Info(args...) +} + +func (l *controlLogger) infof(template string, args ...interface{}) { + l.mu.RLock() + defer l.mu.RUnlock() + l.logger.Infof(template, args...) +} + +func (l *controlLogger) warn(args ...interface{}) { + l.mu.RLock() + defer l.mu.RUnlock() + l.logger.Warn(args...) } -func (l *Logger) GetLoggerObj() *kitexzap.Logger { - return loggerObj +func (l *controlLogger) warnf(template string, args ...interface{}) { + l.mu.RLock() + defer l.mu.RUnlock() + l.logger.Warnf(template, args...) } -func (l *Logger) Printf(template string, args ...interface{}) { - l.Infof(template, args...) +func (l *controlLogger) error(args ...interface{}) { + l.mu.RLock() + defer l.mu.RUnlock() + l.logger.Error(args...) } -func GetLogger() *Logger { - return &Logger{loggerObj} +func (l *controlLogger) errorf(template string, args ...interface{}) { + l.mu.RLock() + defer l.mu.RUnlock() + l.logger.Errorf(template, args...) +} + +func (l *controlLogger) fatal(args ...interface{}) { + l.mu.RLock() + defer l.mu.RUnlock() + l.logger.Fatal(args...) +} + +func (l *controlLogger) fatalf(template string, args ...interface{}) { + l.mu.RLock() + defer l.mu.RUnlock() + l.logger.Fatalf(template, args...) +} + +// LErrorf Equals Errorf less one stack +func LErrorf(template string, args ...interface{}) { + control.mu.RLock() + defer control.mu.RUnlock() + control.logger.Errorf(template, args...) +} + +func parseLevel(level string) zapcore.Level { + var lvl zapcore.Level + switch strings.ToLower(level) { + case "debug": + lvl = zapcore.DebugLevel + case "info": + lvl = zapcore.InfoLevel + case "warn": + lvl = zapcore.WarnLevel + case "error": + lvl = zapcore.ErrorLevel + case "fatal": + lvl = zapcore.FatalLevel + default: + lvl = zapcore.InfoLevel + } + return lvl } diff --git a/pkg/logger/logger_test.go b/pkg/logger/logger_test.go new file mode 100644 index 00000000..5e78bb8e --- /dev/null +++ b/pkg/logger/logger_test.go @@ -0,0 +1,126 @@ +/* +Copyright 2024 The west2-online Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package logger + +import ( + "fmt" + "io" + "os" + "strings" + "testing" + "time" + + . "github.com/bytedance/mockey" + . "github.com/smartystreets/goconvey/convey" + "go.uber.org/zap/zapcore" + + "github.com/west2-online/fzuhelper-server/pkg/constants" +) + +var ( + targetDir = "." + service = "svc" +) + +func Test_updateLogger(t *testing.T) { + now := time.Now() + date := now.Format("2006-01-02") + + PatchConvey("Test updateLogger", t, func() { + Mock(getCurrentDirectory).Return(targetDir, nil).Build() + Mock(time.Now).Return(now).Build() + control.updateLogger(service) + infoMsg := "info" + errorMsg := "error" + Info(infoMsg) + Error(errorMsg) + + PatchConvey("Try open file and read all", func() { + logPath := fmt.Sprintf("%s/%s/%s/%s.log", targetDir, constants.LogFilePath, date, service) + stderrPath := fmt.Sprintf("%s/%s/%s/%s_stderr.log", targetDir, constants.LogFilePath, date, service) + logFile, err := os.Open(logPath) + So(err, ShouldBeNil) + errFile, err := os.Open(stderrPath) + So(err, ShouldBeNil) + + infoLogB, err := io.ReadAll(logFile) + So(err, ShouldBeNil) + errorLogB, err := io.ReadAll(errFile) + So(err, ShouldBeNil) + + PatchConvey("Check result", func() { + infoLog := string(infoLogB) + errorLog := string(errorLogB) + infoFields := strings.Split(infoLog, "\t") + errorFields := strings.Split(errorLog, "\t") + + So(len(infoFields), ShouldEqual, 4) + So(len(infoFields), ShouldEqual, len(errorFields)) + So(len(infoFields[0]), ShouldEqual, len(errorFields[0])) + So(infoFields[1], ShouldEqual, strings.ToUpper(infoMsg)) + So(errorFields[1], ShouldEqual, strings.ToUpper(errorMsg)) + So(len(infoFields[2]), ShouldEqual, len(infoFields[2])) + So(infoFields[3], ShouldEqual, infoMsg+"\n") + So(errorFields[3], ShouldEqual, errorMsg+"\n") + }) + + PatchConvey("Release resource", func() { + So(logFile.Close(), ShouldBeNil) + So(errFile.Close(), ShouldBeNil) + So(os.Remove(logPath), ShouldBeNil) + So(os.Remove(stderrPath), ShouldBeNil) + So(os.Remove(fmt.Sprintf("%s/%s/%s", targetDir, constants.LogFilePath, date)), ShouldBeNil) + _ = os.Remove(fmt.Sprintf("%s/%s", targetDir, constants.LogFilePath)) + }) + }) + }) +} + +func Test_scheduleUpdateLogger(t *testing.T) { + now := time.Now().Truncate(24 * time.Hour).Add(23 * time.Hour).Add(59 * time.Minute).Add(59 * time.Second) + date := now.Format("2006-01-02") + logPath := fmt.Sprintf("%s/%s/%s/%s.log", targetDir, constants.LogFilePath, date, service) + stderrPath := fmt.Sprintf("%s/%s/%s/%s_stderr.log", targetDir, constants.LogFilePath, date, service) + + PatchConvey("Test scheduleUpdateLogger", t, func() { + Mock(getCurrentDirectory).Return(targetDir, nil).Build() + Mock(time.Now).Return(now).Build() + control.scheduleUpdateLogger("svc") + + time.Sleep(3 * time.Second) // waiting for update logger + + So(logFileHandler.Load(), ShouldNotBeNil) + So(stdErrFileHandler.Load(), ShouldNotBeNil) + + PatchConvey("Release resource", func() { + So(os.Remove(logPath), ShouldBeNil) + So(os.Remove(stderrPath), ShouldBeNil) + So(os.Remove(fmt.Sprintf("%s/%s/%s", targetDir, constants.LogFilePath, date)), ShouldBeNil) + _ = os.Remove(fmt.Sprintf("%s/%s", targetDir, constants.LogFilePath)) + }) + }) +} + +func Test_parseLevel(t *testing.T) { + Convey("Test parseLevel", t, func() { + So(parseLevel("Debug"), ShouldEqual, zapcore.DebugLevel) + So(parseLevel("DEBUG"), ShouldEqual, zapcore.DebugLevel) + So(parseLevel("Info"), ShouldEqual, zapcore.InfoLevel) + So(parseLevel("Info"), ShouldEqual, zapcore.InfoLevel) + So(parseLevel(""), ShouldEqual, zapcore.InfoLevel) + }) +} diff --git a/pkg/logger/mysql.go b/pkg/logger/mysql.go new file mode 100644 index 00000000..c3fd1d3f --- /dev/null +++ b/pkg/logger/mysql.go @@ -0,0 +1,27 @@ +/* +Copyright 2024 The west2-online Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package logger + +type MysqlLogger struct{} + +func (l *MysqlLogger) Printf(template string, args ...interface{}) { + Infof(template, args...) +} + +func GetMysqlLogger() *MysqlLogger { + return &MysqlLogger{} +} diff --git a/pkg/logger/out_test.go b/pkg/logger/out_test.go new file mode 100644 index 00000000..4615173d --- /dev/null +++ b/pkg/logger/out_test.go @@ -0,0 +1,42 @@ +/* +Copyright 2024 The west2-online Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package logger + +import ( + "os" + "runtime" + "testing" + + . "github.com/smartystreets/goconvey/convey" +) + +func Test_checkAndOpenFile(t *testing.T) { + Convey("Test checkAndOpenFile", t, func() { + path := "./test.log" + f := checkAndOpenFile(path) + So(f.Name(), ShouldEqual, path) + fi, err := os.Stat(path) + So(err, ShouldBeNil) + So(fi.Name(), ShouldEqual, "test.log") + + // 触发 Finalizer + f = nil + runtime.GC() + + So(os.Remove(path), ShouldBeNil) + }) +} diff --git a/pkg/logger/output.go b/pkg/logger/output.go index 9e814c60..6f7ac815 100644 --- a/pkg/logger/output.go +++ b/pkg/logger/output.go @@ -17,50 +17,79 @@ limitations under the License. package logger import ( - "github.com/cloudwego/kitex/pkg/klog" + "os" + "path/filepath" + "runtime" + "strings" ) func Debug(args ...interface{}) { - klog.Debug(args...) + control.debug(args...) } func Debugf(template string, args ...interface{}) { - klog.Debugf(template, args...) + control.debugf(template, args...) } func Info(args ...interface{}) { - klog.Info(args...) + control.info(args...) } func Infof(template string, args ...interface{}) { - klog.Infof(template, args...) + control.infof(template, args...) } func Warn(args ...interface{}) { - klog.Warn(args...) + control.warn(args...) } func Warnf(template string, args ...interface{}) { - klog.Warnf(template, args...) + control.warnf(template, args...) } func Error(args ...interface{}) { - klog.Error(args...) + control.error(args...) } func Errorf(template string, args ...interface{}) { - klog.Errorf(template, args...) + control.errorf(template, args...) } func Fatal(args ...interface{}) { - klog.Fatal(args...) + control.fatal(args...) } func Fatalf(template string, args ...interface{}) { - klog.Fatalf(template, args...) + control.fatalf(template, args...) } -// LErrorf Equals Errorf less one stack -func LErrorf(template string, args ...interface{}) { - loggerObj.Errorf(template, args...) +const permission = 0o755 // 用户具有读/写/执行权限,组用户和其它用户具有读写权限 + +// getCurrentDirectory 会返回当前运行的目录 +func getCurrentDirectory() (string, error) { + dir, err := filepath.Abs(filepath.Dir(os.Args[0])) + if err != nil { + return "", err + } + + return strings.ReplaceAll(dir, "\\", "/"), nil +} + +func checkAndOpenFile(path string) *os.File { + var err error + var handler *os.File + if err = os.MkdirAll(filepath.Dir(path), permission); err != nil { + panic(err) + } + + handler, err = os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, permission) + if err != nil { + panic(err) + } + runtime.SetFinalizer(handler, func(fd *os.File) { + if err := fd.Close(); err != nil { + Infof("close file failed %v", err) + } + }) + return handler } diff --git a/pkg/logger/redis.go b/pkg/logger/redis.go index 7fc34fa1..ec18d57f 100644 --- a/pkg/logger/redis.go +++ b/pkg/logger/redis.go @@ -21,18 +21,16 @@ import ( "net" "time" - kitexzap "github.com/kitex-contrib/obs-opentelemetry/logging/zap" "github.com/redis/go-redis/v9" "github.com/west2-online/fzuhelper-server/pkg/constants" ) -type RedisLogger struct { - *kitexzap.Logger -} +// RedisLogger 不加入自定义的 logger 字段, 以使得 logger 更新后无指针引用 +type RedisLogger struct{} func (l *RedisLogger) Printf(ctx context.Context, template string, args ...interface{}) { - l.Infof(template, args...) + Infof(template, args...) } func (l *RedisLogger) DialHook(next redis.DialHook) redis.DialHook { @@ -65,5 +63,5 @@ func (l *RedisLogger) ProcessPipelineHook(next redis.ProcessPipelineHook) redis. } func GetRedisLogger() *RedisLogger { - return &RedisLogger{loggerObj} + return &RedisLogger{} }