Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d36d66bbf7 | |||
| d3978e1f60 | |||
| 616abd2364 | |||
| 3b4b9952dc | |||
| 3005002379 | |||
| b3e319a21f | |||
| 078967c601 | |||
| 424ad78a7e | |||
| 5213f7002f | |||
| fe341735dd | |||
| 20f500ebcf | |||
| 9dc56ebe60 |
36
go.mod
36
go.mod
@@ -1,26 +1,26 @@
|
||||
module gitea.bvbej.com/bvbej/base-golang
|
||||
|
||||
go 1.25.4
|
||||
go 1.25.6
|
||||
|
||||
require (
|
||||
github.com/apolloconfig/agollo/v4 v4.4.0
|
||||
github.com/gin-contrib/pprof v1.5.3
|
||||
github.com/gin-gonic/gin v1.11.0
|
||||
github.com/go-playground/validator/v10 v10.28.0
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0
|
||||
github.com/go-playground/validator/v10 v10.30.1
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/jinzhu/now v1.1.5
|
||||
github.com/json-iterator/go v1.1.12
|
||||
github.com/mojocn/base64Captcha v1.3.8
|
||||
github.com/mritd/chinaid v1.0.4
|
||||
github.com/panjf2000/ants/v2 v2.11.3
|
||||
github.com/panjf2000/ants/v2 v2.11.5
|
||||
github.com/prometheus/client_golang v1.23.2
|
||||
github.com/qiniu/go-sdk/v7 v7.25.5
|
||||
github.com/redis/go-redis/v9 v9.17.2
|
||||
github.com/qiniu/go-sdk/v7 v7.25.6
|
||||
github.com/redis/go-redis/v9 v9.17.3
|
||||
github.com/robfig/cron/v3 v3.0.1
|
||||
github.com/rs/cors v1.11.1
|
||||
github.com/rs/cors/wrapper/gin v0.0.0-20240830163046-1084d89a1692
|
||||
github.com/rs/cors/wrapper/gin v0.0.0-20260123235804-c9e5260a4ed4
|
||||
github.com/speps/go-hashids v2.0.0+incompatible
|
||||
github.com/spf13/cast v1.10.0
|
||||
github.com/spf13/viper v1.21.0
|
||||
@@ -29,16 +29,16 @@ require (
|
||||
github.com/tidwall/gjson v1.18.0
|
||||
github.com/tus/tusd v1.13.0
|
||||
github.com/xuri/excelize/v2 v2.10.0
|
||||
go.mongodb.org/mongo-driver v1.17.6
|
||||
go.mongodb.org/mongo-driver v1.17.9
|
||||
go.uber.org/atomic v1.11.0
|
||||
go.uber.org/multierr v1.11.0
|
||||
go.uber.org/zap v1.27.1
|
||||
golang.org/x/crypto v0.46.0
|
||||
golang.org/x/net v0.48.0
|
||||
golang.org/x/crypto v0.47.0
|
||||
golang.org/x/net v0.49.0
|
||||
golang.org/x/sync v0.19.0
|
||||
golang.org/x/time v0.14.0
|
||||
google.golang.org/grpc v1.77.0
|
||||
google.golang.org/protobuf v1.36.10
|
||||
google.golang.org/grpc v1.78.0
|
||||
google.golang.org/protobuf v1.36.11
|
||||
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1
|
||||
gorm.io/driver/mysql v1.6.0
|
||||
@@ -58,7 +58,7 @@ require (
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.10 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||
github.com/gammazero/toposort v0.1.1 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
@@ -113,11 +113,11 @@ require (
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/arch v0.20.0 // indirect
|
||||
golang.org/x/image v0.25.0 // indirect
|
||||
golang.org/x/mod v0.30.0 // indirect
|
||||
golang.org/x/sys v0.39.0 // indirect
|
||||
golang.org/x/text v0.32.0 // indirect
|
||||
golang.org/x/tools v0.39.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251022142026-3a174f9686a8 // indirect
|
||||
golang.org/x/mod v0.31.0 // indirect
|
||||
golang.org/x/sys v0.40.0 // indirect
|
||||
golang.org/x/text v0.33.0 // indirect
|
||||
golang.org/x/tools v0.40.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda // indirect
|
||||
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
modernc.org/fileutil v1.0.0 // indirect
|
||||
|
||||
68
go.sum
68
go.sum
@@ -884,8 +884,8 @@ github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7z
|
||||
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gammazero/toposort v0.1.1 h1:OivGxsWxF3U3+U80VoLJ+f50HcPU1MIqE1JlKzoJ2Eg=
|
||||
github.com/gammazero/toposort v0.1.1/go.mod h1:H2cozTnNpMw0hg2VHAYsAxmkHXBYroNangj2NTBQDvw=
|
||||
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
|
||||
@@ -932,8 +932,8 @@ github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.7.0/go.mod h1:xm76BBt941f7yWdGnI2DVPFFg1UK3YY04qifoXU3lOk=
|
||||
github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688=
|
||||
github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU=
|
||||
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
|
||||
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
|
||||
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||
@@ -949,8 +949,8 @@ github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw=
|
||||
github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU=
|
||||
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
|
||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||
@@ -1199,8 +1199,8 @@ github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRW
|
||||
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
|
||||
github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms=
|
||||
github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
|
||||
github.com/panjf2000/ants/v2 v2.11.3 h1:AfI0ngBoXJmYOpDh9m516vjqoUu2sLrIVgppI9TZVpg=
|
||||
github.com/panjf2000/ants/v2 v2.11.3/go.mod h1:8u92CYMUc6gyvTIw8Ru7Mt7+/ESnJahz5EVtqfrilek=
|
||||
github.com/panjf2000/ants/v2 v2.11.5 h1:a7LMnMEeux/ebqTux140tRiaqcFTV0q2bEHF03nl6Rg=
|
||||
github.com/panjf2000/ants/v2 v2.11.5/go.mod h1:8u92CYMUc6gyvTIw8Ru7Mt7+/ESnJahz5EVtqfrilek=
|
||||
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
|
||||
github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
@@ -1252,15 +1252,15 @@ github.com/prometheus/procfs v0.10.1/go.mod h1:nwNm2aOCAYw8uTR/9bWRREkZFxAUcWzPH
|
||||
github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
|
||||
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
|
||||
github.com/qiniu/dyn v1.3.0/go.mod h1:E8oERcm8TtwJiZvkQPbcAh0RL8jO1G0VXJMW3FAWdkk=
|
||||
github.com/qiniu/go-sdk/v7 v7.25.5 h1:BZAZhrYC7vrw9NPnNbFi1K8xucoz29s7sEGWap77i2Q=
|
||||
github.com/qiniu/go-sdk/v7 v7.25.5/go.mod h1:dmKtJ2ahhPWFVi9o1D5GemmWoh/ctuB9peqTowyTO8o=
|
||||
github.com/qiniu/go-sdk/v7 v7.25.6 h1:89KQX16Bv2x7MxhwpzWGGvQBOPIlGpAcnPQyfS3tRok=
|
||||
github.com/qiniu/go-sdk/v7 v7.25.6/go.mod h1:dmKtJ2ahhPWFVi9o1D5GemmWoh/ctuB9peqTowyTO8o=
|
||||
github.com/qiniu/x v1.10.5/go.mod h1:03Ni9tj+N2h2aKnAz+6N0Xfl8FwMEDRC2PAlxekASDs=
|
||||
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
|
||||
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
|
||||
github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=
|
||||
github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
|
||||
github.com/redis/go-redis/v9 v9.17.2 h1:P2EGsA4qVIM3Pp+aPocCJ7DguDHhqrXNhVcEp4ViluI=
|
||||
github.com/redis/go-redis/v9 v9.17.2/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
|
||||
github.com/redis/go-redis/v9 v9.17.3 h1:fN29NdNrE17KttK5Ndf20buqfDZwGNgoUr9qjl1DQx4=
|
||||
github.com/redis/go-redis/v9 v9.17.3/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/richardlehane/mscfb v1.0.4 h1:WULscsljNPConisD5hR0+OyZjwK46Pfyr6mPu5ZawpM=
|
||||
@@ -1279,8 +1279,8 @@ github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjR
|
||||
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
||||
github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=
|
||||
github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
|
||||
github.com/rs/cors/wrapper/gin v0.0.0-20240830163046-1084d89a1692 h1:lwzJgPw5Y6pvC8mwbedX9HfdywUKcpNdcviftZsb1uY=
|
||||
github.com/rs/cors/wrapper/gin v0.0.0-20240830163046-1084d89a1692/go.mod h1:742Ialb8SOs5yB2PqRDzFcyND3280PoaS5/wcKQUQKE=
|
||||
github.com/rs/cors/wrapper/gin v0.0.0-20260123235804-c9e5260a4ed4 h1:o+wYsOfZvOhP3CLGQH5MGVaw9xWjkGIXYH9nJ7NA2FM=
|
||||
github.com/rs/cors/wrapper/gin v0.0.0-20260123235804-c9e5260a4ed4/go.mod h1:UkcVz4d5PVHMbLZcN5lqy4KOGXiO9vVdxlITo+boMCE=
|
||||
github.com/ruudk/golang-pdf417 v0.0.0-20181029194003-1af4ab5afa58/go.mod h1:6lfFZQK844Gfx8o5WFuvpxWRwnSoipWe/p622j1v06w=
|
||||
github.com/ruudk/golang-pdf417 v0.0.0-20201230142125-a7e3863a1245/go.mod h1:pQAZKsJ8yyVxGRWYNEm9oFB8ieLgKFnamEyDmSA0BRk=
|
||||
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
|
||||
@@ -1393,8 +1393,8 @@ github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaD
|
||||
go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs=
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g=
|
||||
go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ=
|
||||
go.mongodb.org/mongo-driver v1.17.6 h1:87JUG1wZfWsr6rIz3ZmpH90rL5tea7O3IHuSwHUpsss=
|
||||
go.mongodb.org/mongo-driver v1.17.6/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ=
|
||||
go.mongodb.org/mongo-driver v1.17.9 h1:IexDdCuuNJ3BHrELgBlyaH9p60JXAvdzWR128q+U5tU=
|
||||
go.mongodb.org/mongo-driver v1.17.9/go.mod h1:LlOhpH5NUEfhxcAwG0UEkMqwYcc4JU18gtCdGudk/tQ=
|
||||
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
|
||||
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
|
||||
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
|
||||
@@ -1461,8 +1461,8 @@ golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98y
|
||||
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
|
||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||
golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8=
|
||||
golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A=
|
||||
golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
@@ -1527,8 +1527,8 @@ golang.org/x/mod v0.10.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk=
|
||||
golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc=
|
||||
golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
|
||||
golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg=
|
||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
@@ -1600,8 +1600,8 @@ golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI=
|
||||
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||
golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
|
||||
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
|
||||
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.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
@@ -1759,8 +1759,8 @@ golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
|
||||
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
@@ -1801,8 +1801,8 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
|
||||
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
|
||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
@@ -1880,8 +1880,8 @@ golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s=
|
||||
golang.org/x/tools v0.9.1/go.mod h1:owI94Op576fPu3cIGQeHs3joujW/2Oc6MtlxbF5dfNc=
|
||||
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ=
|
||||
golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ=
|
||||
golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
|
||||
golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
@@ -2134,8 +2134,8 @@ google.golang.org/genproto/googleapis/rpc v0.0.0-20230706204954-ccb25ca9f130/go.
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20230711160842-782d3b101e98/go.mod h1:TUfxEVdsvPg18p6AslUXFoLdpED4oBnGwyqk3dV1XzM=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20230731190214-cbb8c96f2d6d/go.mod h1:TUfxEVdsvPg18p6AslUXFoLdpED4oBnGwyqk3dV1XzM=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20230807174057-1744710a1577/go.mod h1:+Bk1OCOj40wS2hwAMA+aCW9ypzm63QTBBHp6lQ3p+9M=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251022142026-3a174f9686a8 h1:M1rk8KBnUsBDg1oPGHNCxG4vc1f49epmTO7xscSajMk=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251022142026-3a174f9686a8/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda h1:i/Q+bfisr7gq6feoJnS/DlpdwEL4ihp41fvRiM3Ork0=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=
|
||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
|
||||
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
|
||||
@@ -2181,8 +2181,8 @@ google.golang.org/grpc v1.55.0/go.mod h1:iYEXKGkEBhg1PjZQvoYEVPTDkHo1/bjTnfwTeGO
|
||||
google.golang.org/grpc v1.56.1/go.mod h1:I9bI3vqKfayGqPUAwGdOSu7kt6oIJLixfffKrpXqQ9s=
|
||||
google.golang.org/grpc v1.56.2/go.mod h1:I9bI3vqKfayGqPUAwGdOSu7kt6oIJLixfffKrpXqQ9s=
|
||||
google.golang.org/grpc v1.57.0/go.mod h1:Sd+9RMTACXwmub0zcNY2c4arhtrbBYD1AUHI/dt16Mo=
|
||||
google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM=
|
||||
google.golang.org/grpc v1.77.0/go.mod h1:z0BY1iVj0q8E1uSQCjL9cppRj+gnZjzDnzV0dHhrNig=
|
||||
google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc=
|
||||
google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U=
|
||||
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw=
|
||||
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||
@@ -2202,8 +2202,8 @@ google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqw
|
||||
google.golang.org/protobuf v1.29.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
|
||||
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/Acconut/lockfile.v1 v1.1.0/go.mod h1:6UCz3wJ8tSFUsPR6uP/j8uegEtDuEEqFxlpi0JI4Umw=
|
||||
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
|
||||
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk=
|
||||
|
||||
287
pkg/cache/helper.go
vendored
Normal file
287
pkg/cache/helper.go
vendored
Normal file
@@ -0,0 +1,287 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// ========== 分布式锁 ==========
|
||||
|
||||
// Lock 分布式锁
|
||||
type Lock struct {
|
||||
repo RedisRepo
|
||||
key string
|
||||
value string
|
||||
expiry time.Duration
|
||||
}
|
||||
|
||||
// NewLock 创建分布式锁
|
||||
func NewLock(repo RedisRepo, key, value string, expiry time.Duration) *Lock {
|
||||
return &Lock{
|
||||
repo: repo,
|
||||
key: key,
|
||||
value: value,
|
||||
expiry: expiry,
|
||||
}
|
||||
}
|
||||
|
||||
// Acquire 获取锁
|
||||
func (l *Lock) Acquire(ctx context.Context) (bool, error) {
|
||||
return l.repo.SetNX(ctx, l.key, l.value, l.expiry)
|
||||
}
|
||||
|
||||
// Release 释放锁
|
||||
func (l *Lock) Release(ctx context.Context) error {
|
||||
script := redis.NewScript(`
|
||||
if redis.call("get", KEYS[1]) == ARGV[1] then
|
||||
return redis.call("del", KEYS[1])
|
||||
else
|
||||
return 0
|
||||
end
|
||||
`)
|
||||
|
||||
return script.Run(ctx, l.repo.Client(), []string{l.key}, l.value).Err()
|
||||
}
|
||||
|
||||
// Refresh 刷新锁
|
||||
func (l *Lock) Refresh(ctx context.Context) (bool, error) {
|
||||
script := redis.NewScript(`
|
||||
if redis.call("get", KEYS[1]) == ARGV[1] then
|
||||
return redis.call("pexpire", KEYS[1], ARGV[2])
|
||||
else
|
||||
return 0
|
||||
end
|
||||
`)
|
||||
|
||||
result, err := script.Run(ctx, l.repo.Client(), []string{l.key}, l.value, l.expiry.Milliseconds()).Result()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return result.(int64) == 1, nil
|
||||
}
|
||||
|
||||
// ========== JSON 序列化 ==========
|
||||
|
||||
// SetJSON 设置JSON对象
|
||||
func SetJSON(ctx context.Context, repo RedisRepo, key string, value interface{}, ttl time.Duration) error {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("json marshal 失败: %w", err)
|
||||
}
|
||||
return repo.Set(ctx, key, string(data), ttl)
|
||||
}
|
||||
|
||||
// GetJSON 获取JSON对象
|
||||
func GetJSON(ctx context.Context, repo RedisRepo, key string, dest interface{}) error {
|
||||
val, err := repo.Get(ctx, key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if val == "" {
|
||||
return errors.New("key 不存在")
|
||||
}
|
||||
|
||||
if err := json.Unmarshal([]byte(val), dest); err != nil {
|
||||
return fmt.Errorf("json unmarshal 失败: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ========== 限流器 ==========
|
||||
|
||||
// RateLimiter 限流器(令牌桶算法)
|
||||
type RateLimiter struct {
|
||||
repo RedisRepo
|
||||
key string
|
||||
limit int64 // 最大令牌数
|
||||
interval time.Duration // 时间窗口
|
||||
}
|
||||
|
||||
// NewRateLimiter 创建限流器
|
||||
func NewRateLimiter(repo RedisRepo, key string, limit int64, interval time.Duration) *RateLimiter {
|
||||
return &RateLimiter{
|
||||
repo: repo,
|
||||
key: key,
|
||||
limit: limit,
|
||||
interval: interval,
|
||||
}
|
||||
}
|
||||
|
||||
// Allow 检查是否允许(简单计数器实现)
|
||||
func (r *RateLimiter) Allow(ctx context.Context) (bool, error) {
|
||||
pipe := r.repo.Pipeline()
|
||||
|
||||
incrCmd := pipe.Incr(ctx, r.key)
|
||||
pipe.Expire(ctx, r.key, r.interval)
|
||||
|
||||
if _, err := pipe.Exec(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
count, err := incrCmd.Result()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return count <= r.limit, nil
|
||||
}
|
||||
|
||||
// AllowN 检查是否允许N次
|
||||
func (r *RateLimiter) AllowN(ctx context.Context, n int64) (bool, error) {
|
||||
pipe := r.repo.Pipeline()
|
||||
|
||||
incrCmd := pipe.IncrBy(ctx, r.key, n)
|
||||
pipe.Expire(ctx, r.key, r.interval)
|
||||
|
||||
if _, err := pipe.Exec(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
count, err := incrCmd.Result()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return count <= r.limit, nil
|
||||
}
|
||||
|
||||
// Remaining 获取剩余次数
|
||||
func (r *RateLimiter) Remaining(ctx context.Context) (int64, error) {
|
||||
val, err := r.repo.Get(ctx, r.key)
|
||||
if err != nil {
|
||||
return r.limit, nil
|
||||
}
|
||||
if val == "" {
|
||||
return r.limit, nil
|
||||
}
|
||||
|
||||
var count int64
|
||||
if _, err := fmt.Sscanf(val, "%d", &count); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
remaining := r.limit - count
|
||||
if remaining < 0 {
|
||||
remaining = 0
|
||||
}
|
||||
|
||||
return remaining, nil
|
||||
}
|
||||
|
||||
// Reset 重置限流器
|
||||
func (r *RateLimiter) Reset(ctx context.Context) error {
|
||||
_, err := r.repo.Del(ctx, r.key)
|
||||
return err
|
||||
}
|
||||
|
||||
// ========== 缓存装饰器 ==========
|
||||
|
||||
// CacheDecorator 缓存装饰器
|
||||
type CacheDecorator struct {
|
||||
repo RedisRepo
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
// NewCacheDecorator 创建缓存装饰器
|
||||
func NewCacheDecorator(repo RedisRepo, ttl time.Duration) *CacheDecorator {
|
||||
return &CacheDecorator{
|
||||
repo: repo,
|
||||
ttl: ttl,
|
||||
}
|
||||
}
|
||||
|
||||
// GetOrSet 获取或设置缓存
|
||||
func (c *CacheDecorator) GetOrSet(ctx context.Context, key string, dest interface{}, loader func() (interface{}, error)) error {
|
||||
// 尝试从缓存获取
|
||||
err := GetJSON(ctx, c.repo, key, dest)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 缓存未命中,执行加载函数
|
||||
data, err := loader()
|
||||
if err != nil {
|
||||
return fmt.Errorf("loader 执行失败: %w", err)
|
||||
}
|
||||
|
||||
// 设置缓存
|
||||
if err := SetJSON(ctx, c.repo, key, data, c.ttl); err != nil {
|
||||
// 缓存设置失败不影响主流程
|
||||
// 可以记录日志
|
||||
}
|
||||
|
||||
// 将数据赋值给dest
|
||||
dataBytes, _ := json.Marshal(data)
|
||||
return json.Unmarshal(dataBytes, dest)
|
||||
}
|
||||
|
||||
// ========== 布隆过滤器(简单实现) ==========
|
||||
|
||||
// BloomFilter 布隆过滤器
|
||||
type BloomFilter struct {
|
||||
repo RedisRepo
|
||||
key string
|
||||
size uint64
|
||||
}
|
||||
|
||||
// NewBloomFilter 创建布隆过滤器
|
||||
func NewBloomFilter(repo RedisRepo, key string, size uint64) *BloomFilter {
|
||||
return &BloomFilter{
|
||||
repo: repo,
|
||||
key: key,
|
||||
size: size,
|
||||
}
|
||||
}
|
||||
|
||||
// Add 添加元素
|
||||
func (b *BloomFilter) Add(ctx context.Context, value string) error {
|
||||
// 简单hash
|
||||
hash1 := hashString(value, 0) % b.size
|
||||
hash2 := hashString(value, 1) % b.size
|
||||
hash3 := hashString(value, 2) % b.size
|
||||
|
||||
pipe := b.repo.Pipeline()
|
||||
pipe.SetBit(ctx, b.key, int64(hash1), 1)
|
||||
pipe.SetBit(ctx, b.key, int64(hash2), 1)
|
||||
pipe.SetBit(ctx, b.key, int64(hash3), 1)
|
||||
|
||||
_, err := pipe.Exec(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// Exists 检查元素是否存在
|
||||
func (b *BloomFilter) Exists(ctx context.Context, value string) (bool, error) {
|
||||
hash1 := hashString(value, 0) % b.size
|
||||
hash2 := hashString(value, 1) % b.size
|
||||
hash3 := hashString(value, 2) % b.size
|
||||
|
||||
pipe := b.repo.Pipeline()
|
||||
bit1Cmd := pipe.GetBit(ctx, b.key, int64(hash1))
|
||||
bit2Cmd := pipe.GetBit(ctx, b.key, int64(hash2))
|
||||
bit3Cmd := pipe.GetBit(ctx, b.key, int64(hash3))
|
||||
|
||||
if _, err := pipe.Exec(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
bit1, _ := bit1Cmd.Result()
|
||||
bit2, _ := bit2Cmd.Result()
|
||||
bit3, _ := bit3Cmd.Result()
|
||||
|
||||
return bit1 == 1 && bit2 == 1 && bit3 == 1, nil
|
||||
}
|
||||
|
||||
// hashString 简单字符串hash
|
||||
func hashString(s string, seed uint64) uint64 {
|
||||
hash := seed
|
||||
for i := 0; i < len(s); i++ {
|
||||
hash = hash*31 + uint64(s[i])
|
||||
}
|
||||
return hash
|
||||
}
|
||||
1127
pkg/cache/redis.go
vendored
1127
pkg/cache/redis.go
vendored
File diff suppressed because it is too large
Load Diff
71
pkg/crypto/aes.go
Normal file
71
pkg/crypto/aes.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// AESEncryptor AES-GCM加密器
|
||||
type AESEncryptor struct {
|
||||
key []byte
|
||||
}
|
||||
|
||||
// NewAESEncryptor 创建AES加密器
|
||||
func NewAESEncryptor(key string) (*AESEncryptor, error) {
|
||||
// 使用SHA256生成32字节密钥
|
||||
hash := sha256.Sum256([]byte(key))
|
||||
return &AESEncryptor{key: hash[:]}, nil
|
||||
}
|
||||
|
||||
func (e *AESEncryptor) Encrypt(plaintext []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(e.key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建cipher失败: %w", err)
|
||||
}
|
||||
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建GCM失败: %w", err)
|
||||
}
|
||||
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return nil, fmt.Errorf("生成nonce失败: %w", err)
|
||||
}
|
||||
|
||||
ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
|
||||
return ciphertext, nil
|
||||
}
|
||||
|
||||
func (e *AESEncryptor) Decrypt(ciphertext []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(e.key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建cipher失败: %w", err)
|
||||
}
|
||||
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建GCM失败: %w", err)
|
||||
}
|
||||
|
||||
nonceSize := gcm.NonceSize()
|
||||
if len(ciphertext) < nonceSize {
|
||||
return nil, fmt.Errorf("密文长度不足")
|
||||
}
|
||||
|
||||
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
|
||||
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解密失败: %w", err)
|
||||
}
|
||||
|
||||
return plaintext, nil
|
||||
}
|
||||
|
||||
func (e *AESEncryptor) Name() string {
|
||||
return "AES-GCM-256"
|
||||
}
|
||||
202
pkg/crypto/client/axios/encryptedAxios.ts
Normal file
202
pkg/crypto/client/axios/encryptedAxios.ts
Normal file
@@ -0,0 +1,202 @@
|
||||
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
|
||||
import { IEncryptor, ISigner, CryptoConfig, EncryptedRequest, EncryptedResponse } from '../crypto/interface';
|
||||
import { uint8ArrayToBase64, base64ToUint8Array, stringToUint8Array, uint8ArrayToString } from '../utils/base64';
|
||||
import { generateUUID } from '../utils/uuid';
|
||||
|
||||
/**
|
||||
* 加密Axios实例
|
||||
*/
|
||||
export class EncryptedAxios {
|
||||
private axiosInstance: AxiosInstance;
|
||||
private encryptor: IEncryptor | null = null;
|
||||
private signer: ISigner | null = null;
|
||||
private config: CryptoConfig;
|
||||
|
||||
constructor(
|
||||
encryptor?: IEncryptor,
|
||||
signer?: ISigner,
|
||||
config: CryptoConfig = {},
|
||||
axiosConfig?: AxiosRequestConfig
|
||||
) {
|
||||
this.encryptor = encryptor || null;
|
||||
this.signer = signer || null;
|
||||
this.config = {
|
||||
timestampWindow: 5 * 60 * 1000, // 默认5分钟
|
||||
enableTimestamp: true,
|
||||
enableSignature: true,
|
||||
...config,
|
||||
};
|
||||
|
||||
// 创建axios实例
|
||||
this.axiosInstance = axios.create(axiosConfig);
|
||||
|
||||
// 添加请求拦截器
|
||||
this.axiosInstance.interceptors.request.use(
|
||||
this.encryptRequestInterceptor.bind(this),
|
||||
(error) => Promise.reject(error)
|
||||
);
|
||||
|
||||
// 添加响应拦截器
|
||||
this.axiosInstance.interceptors.response.use(
|
||||
this.decryptResponseInterceptor.bind(this),
|
||||
(error) => Promise.reject(error)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求拦截器 - 加密请求数据
|
||||
*/
|
||||
private async encryptRequestInterceptor(
|
||||
config: InternalAxiosRequestConfig
|
||||
): Promise<InternalAxiosRequestConfig> {
|
||||
// 放行GET和OPTIONS请求
|
||||
if (config.method?.toUpperCase() === 'GET' || config.method?.toUpperCase() === 'OPTIONS') {
|
||||
return config;
|
||||
}
|
||||
|
||||
// 如果没有配置加密器,直接返回
|
||||
if (!this.encryptor) {
|
||||
return config;
|
||||
}
|
||||
|
||||
try {
|
||||
// 将请求数据转换为JSON字符串
|
||||
const plaintext = JSON.stringify(config.data || {});
|
||||
const plaintextBytes = stringToUint8Array(plaintext);
|
||||
|
||||
// 加密数据
|
||||
const ciphertext = await this.encryptor.encrypt(plaintextBytes);
|
||||
const encryptedData = uint8ArrayToBase64(ciphertext);
|
||||
|
||||
// 构建加密请求体
|
||||
const encryptedRequest: EncryptedRequest = {
|
||||
data: encryptedData,
|
||||
timestamp: Date.now(),
|
||||
request_id: generateUUID(),
|
||||
algorithm: this.encryptor.name(),
|
||||
};
|
||||
|
||||
// 生成签名
|
||||
if (this.config.enableSignature && this.signer) {
|
||||
const signature = await this.signer.sign(plaintextBytes);
|
||||
encryptedRequest.signature = uint8ArrayToBase64(signature);
|
||||
}
|
||||
|
||||
// 替换请求数据
|
||||
config.data = encryptedRequest;
|
||||
config.headers['Content-Type'] = 'application/json';
|
||||
|
||||
// 保存request_id供响应使用
|
||||
config.headers['X-Request-ID'] = encryptedRequest.request_id;
|
||||
|
||||
} catch (error) {
|
||||
console.error('加密请求失败:', error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* 响应拦截器 - 解密响应数据
|
||||
*/
|
||||
private async decryptResponseInterceptor(
|
||||
response: AxiosResponse
|
||||
): Promise<AxiosResponse> {
|
||||
// 如果没有配置加密器或响应不是加密格式,直接返回
|
||||
if (!this.encryptor || !response.data || typeof response.data !== 'object') {
|
||||
return response;
|
||||
}
|
||||
|
||||
// 检查是否是加密响应
|
||||
const encryptedResponse = response.data as EncryptedResponse;
|
||||
if (!encryptedResponse.data || !encryptedResponse.request_id) {
|
||||
// 不是加密响应,直接返回
|
||||
return response;
|
||||
}
|
||||
|
||||
try {
|
||||
// 验证时间戳
|
||||
if (this.config.enableTimestamp) {
|
||||
this.verifyTimestamp(encryptedResponse.timestamp);
|
||||
}
|
||||
|
||||
// 解密数据
|
||||
const ciphertext = base64ToUint8Array(encryptedResponse.data);
|
||||
const plaintext = await this.encryptor.decrypt(ciphertext);
|
||||
|
||||
// 验证签名
|
||||
if (this.config.enableSignature && this.signer && encryptedResponse.signature) {
|
||||
const signature = base64ToUint8Array(encryptedResponse.signature);
|
||||
const isValid = await this.signer.verify(plaintext, signature);
|
||||
if (!isValid) {
|
||||
throw new Error('签名验证失败');
|
||||
}
|
||||
}
|
||||
|
||||
// 将解密后的数据转换为JSON对象
|
||||
const decryptedData = uint8ArrayToString(plaintext);
|
||||
response.data = JSON.parse(decryptedData);
|
||||
|
||||
} catch (error) {
|
||||
console.error('解密响应失败:', error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证时间戳
|
||||
*/
|
||||
private verifyTimestamp(timestamp: number): void {
|
||||
const now = Date.now();
|
||||
const diff = Math.abs(now - timestamp);
|
||||
|
||||
if (diff > (this.config.timestampWindow || 5 * 60 * 1000)) {
|
||||
throw new Error('请求超时');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取axios实例
|
||||
*/
|
||||
getInstance(): AxiosInstance {
|
||||
return this.axiosInstance;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET 请求
|
||||
*/
|
||||
get<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
|
||||
return this.axiosInstance.get<T>(url, config);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST 请求
|
||||
*/
|
||||
post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
|
||||
return this.axiosInstance.post<T>(url, data, config);
|
||||
}
|
||||
|
||||
/**
|
||||
* PUT 请求
|
||||
*/
|
||||
put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
|
||||
return this.axiosInstance.put<T>(url, data, config);
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE 请求
|
||||
*/
|
||||
delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
|
||||
return this.axiosInstance.delete<T>(url, config);
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH 请求
|
||||
*/
|
||||
patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
|
||||
return this.axiosInstance.patch<T>(url, data, config);
|
||||
}
|
||||
}
|
||||
90
pkg/crypto/client/crypto/aes.ts
Normal file
90
pkg/crypto/client/crypto/aes.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import { IEncryptor } from './interface';
|
||||
|
||||
/**
|
||||
* AES-GCM加密器
|
||||
*/
|
||||
export class AESEncryptor implements IEncryptor {
|
||||
private key: CryptoKey | null = null;
|
||||
|
||||
constructor(keyString: string) {
|
||||
this.importKey(keyString);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入密钥
|
||||
*/
|
||||
private async importKey(keyString: string): Promise<void> {
|
||||
const encoder = new TextEncoder();
|
||||
const keyData = encoder.encode(keyString.padEnd(32, '0').substring(0, 32));
|
||||
|
||||
this.key = await crypto.subtle.importKey(
|
||||
'raw',
|
||||
keyData,
|
||||
{
|
||||
name: 'AES-GCM',
|
||||
length: 256,
|
||||
},
|
||||
false,
|
||||
['encrypt', 'decrypt']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密数据
|
||||
*/
|
||||
async encrypt(plaintext: Uint8Array): Promise<Uint8Array> {
|
||||
if (!this.key) {
|
||||
throw new Error('密钥未设置');
|
||||
}
|
||||
|
||||
// 生成随机IV
|
||||
const iv = crypto.getRandomValues(new Uint8Array(12));
|
||||
|
||||
const encrypted = await crypto.subtle.encrypt(
|
||||
{
|
||||
name: 'AES-GCM',
|
||||
iv: iv,
|
||||
},
|
||||
this.key,
|
||||
plaintext
|
||||
);
|
||||
|
||||
// 将IV和密文拼接在一起
|
||||
const result = new Uint8Array(iv.length + encrypted.byteLength);
|
||||
result.set(iv, 0);
|
||||
result.set(new Uint8Array(encrypted), iv.length);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密数据
|
||||
*/
|
||||
async decrypt(ciphertext: Uint8Array): Promise<Uint8Array> {
|
||||
if (!this.key) {
|
||||
throw new Error('密钥未设置');
|
||||
}
|
||||
|
||||
// 提取IV
|
||||
const iv = ciphertext.slice(0, 12);
|
||||
const data = ciphertext.slice(12);
|
||||
|
||||
const decrypted = await crypto.subtle.decrypt(
|
||||
{
|
||||
name: 'AES-GCM',
|
||||
iv: iv,
|
||||
},
|
||||
this.key,
|
||||
data
|
||||
);
|
||||
|
||||
return new Uint8Array(decrypted);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回算法名称
|
||||
*/
|
||||
name(): string {
|
||||
return 'AES-GCM-256';
|
||||
}
|
||||
}
|
||||
54
pkg/crypto/client/crypto/hmac.ts
Normal file
54
pkg/crypto/client/crypto/hmac.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { ISigner } from './interface';
|
||||
|
||||
/**
|
||||
* HMAC签名器
|
||||
*/
|
||||
export class HMACSigner implements ISigner {
|
||||
private key: CryptoKey | null = null;
|
||||
|
||||
constructor(keyString: string) {
|
||||
this.importKey(keyString);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入密钥
|
||||
*/
|
||||
private async importKey(keyString: string): Promise<void> {
|
||||
const encoder = new TextEncoder();
|
||||
const keyData = encoder.encode(keyString);
|
||||
|
||||
this.key = await crypto.subtle.importKey(
|
||||
'raw',
|
||||
keyData,
|
||||
{
|
||||
name: 'HMAC',
|
||||
hash: 'SHA-256',
|
||||
},
|
||||
false,
|
||||
['sign', 'verify']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成签名
|
||||
*/
|
||||
async sign(data: Uint8Array): Promise<Uint8Array> {
|
||||
if (!this.key) {
|
||||
throw new Error('密钥未设置');
|
||||
}
|
||||
|
||||
const signature = await crypto.subtle.sign('HMAC', this.key, data);
|
||||
return new Uint8Array(signature);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证签名
|
||||
*/
|
||||
async verify(data: Uint8Array, signature: Uint8Array): Promise<boolean> {
|
||||
if (!this.key) {
|
||||
throw new Error('密钥未设置');
|
||||
}
|
||||
|
||||
return await crypto.subtle.verify('HMAC', this.key, signature, data);
|
||||
}
|
||||
}
|
||||
50
pkg/crypto/client/crypto/interface.ts
Normal file
50
pkg/crypto/client/crypto/interface.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* 加密器接口
|
||||
*/
|
||||
export interface IEncryptor {
|
||||
encrypt(plaintext: Uint8Array): Promise<Uint8Array>;
|
||||
decrypt(ciphertext: Uint8Array): Promise<Uint8Array>;
|
||||
name(): string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 签名器接口
|
||||
*/
|
||||
export interface ISigner {
|
||||
sign(data: Uint8Array): Promise<Uint8Array>;
|
||||
verify(data: Uint8Array, signature: Uint8Array): Promise<boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置选项
|
||||
*/
|
||||
export interface CryptoConfig {
|
||||
secretKey?: string; // 对称加密密钥
|
||||
signKey?: string; // 签名密钥
|
||||
publicKey?: string; // RSA公钥(PEM格式)
|
||||
privateKey?: string; // RSA私钥(PEM格式)
|
||||
timestampWindow?: number; // 时间戳窗口(毫秒)
|
||||
enableTimestamp?: boolean; // 是否启用时间戳验证
|
||||
enableSignature?: boolean; // 是否启用签名
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密请求体
|
||||
*/
|
||||
export interface EncryptedRequest {
|
||||
data: string; // Base64编码的加密数据
|
||||
signature?: string; // Base64编码的签名
|
||||
timestamp: number; // 时间戳
|
||||
request_id: string; // 请求ID
|
||||
algorithm: string; // 加密算法名称
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密响应体
|
||||
*/
|
||||
export interface EncryptedResponse {
|
||||
data: string; // Base64编码的加密数据
|
||||
signature?: string; // Base64编码的签名
|
||||
timestamp: number; // 时间戳
|
||||
request_id: string; // 请求ID
|
||||
}
|
||||
125
pkg/crypto/client/crypto/rsa.ts
Normal file
125
pkg/crypto/client/crypto/rsa.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
import { IEncryptor } from './interface';
|
||||
|
||||
/**
|
||||
* RSA加密器(使用Web Crypto API)
|
||||
*/
|
||||
export class RSAEncryptor implements IEncryptor {
|
||||
private publicKey: CryptoKey | null = null;
|
||||
private privateKey: CryptoKey | null = null;
|
||||
|
||||
constructor(publicKeyPEM?: string, privateKeyPEM?: string) {
|
||||
if (publicKeyPEM) {
|
||||
this.importPublicKey(publicKeyPEM);
|
||||
}
|
||||
if (privateKeyPEM) {
|
||||
this.importPrivateKey(privateKeyPEM);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入公钥(PEM格式)
|
||||
*/
|
||||
private async importPublicKey(pem: string): Promise<void> {
|
||||
const pemHeader = '-----BEGIN PUBLIC KEY-----';
|
||||
const pemFooter = '-----END PUBLIC KEY-----';
|
||||
const pemContents = pem
|
||||
.replace(pemHeader, '')
|
||||
.replace(pemFooter, '')
|
||||
.replace(/\s/g, '');
|
||||
|
||||
const binaryDer = this.base64ToArrayBuffer(pemContents);
|
||||
|
||||
this.publicKey = await crypto.subtle.importKey(
|
||||
'spki',
|
||||
binaryDer,
|
||||
{
|
||||
name: 'RSA-OAEP',
|
||||
hash: 'SHA-256',
|
||||
},
|
||||
true,
|
||||
['encrypt']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入私钥(PEM格式)
|
||||
*/
|
||||
private async importPrivateKey(pem: string): Promise<void> {
|
||||
const pemHeader = '-----BEGIN PRIVATE KEY-----';
|
||||
const pemFooter = '-----END PRIVATE KEY-----';
|
||||
const pemContents = pem
|
||||
.replace(pemHeader, '')
|
||||
.replace(pemFooter, '')
|
||||
.replace(/\s/g, '');
|
||||
|
||||
const binaryDer = this.base64ToArrayBuffer(pemContents);
|
||||
|
||||
this.privateKey = await crypto.subtle.importKey(
|
||||
'pkcs8',
|
||||
binaryDer,
|
||||
{
|
||||
name: 'RSA-OAEP',
|
||||
hash: 'SHA-256',
|
||||
},
|
||||
true,
|
||||
['decrypt']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64转ArrayBuffer
|
||||
*/
|
||||
private base64ToArrayBuffer(base64: string): ArrayBuffer {
|
||||
const binaryString = atob(base64);
|
||||
const bytes = new Uint8Array(binaryString.length);
|
||||
for (let i = 0; i < binaryString.length; i++) {
|
||||
bytes[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密数据
|
||||
*/
|
||||
async encrypt(plaintext: Uint8Array): Promise<Uint8Array> {
|
||||
if (!this.publicKey) {
|
||||
throw new Error('公钥未设置');
|
||||
}
|
||||
|
||||
const encrypted = await crypto.subtle.encrypt(
|
||||
{
|
||||
name: 'RSA-OAEP',
|
||||
},
|
||||
this.publicKey,
|
||||
plaintext
|
||||
);
|
||||
|
||||
return new Uint8Array(encrypted);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密数据
|
||||
*/
|
||||
async decrypt(ciphertext: Uint8Array): Promise<Uint8Array> {
|
||||
if (!this.privateKey) {
|
||||
throw new Error('私钥未设置');
|
||||
}
|
||||
|
||||
const decrypted = await crypto.subtle.decrypt(
|
||||
{
|
||||
name: 'RSA-OAEP',
|
||||
},
|
||||
this.privateKey,
|
||||
ciphertext
|
||||
);
|
||||
|
||||
return new Uint8Array(decrypted);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回算法名称
|
||||
*/
|
||||
name(): string {
|
||||
return 'RSA-OAEP-SHA256';
|
||||
}
|
||||
}
|
||||
7
pkg/crypto/client/index.ts
Normal file
7
pkg/crypto/client/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export * from './crypto/interface';
|
||||
export * from './crypto/rsa';
|
||||
export * from './crypto/hmac';
|
||||
export * from './crypto/aes';
|
||||
export * from './axios/encryptedAxios';
|
||||
export * from './utils/base64';
|
||||
export * from './utils/uuid';
|
||||
38
pkg/crypto/client/utils/base64.ts
Normal file
38
pkg/crypto/client/utils/base64.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Uint8Array 转 Base64
|
||||
*/
|
||||
export function uint8ArrayToBase64(bytes: Uint8Array): string {
|
||||
let binary = '';
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
binary += String.fromCharCode(bytes[i]);
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64 转 Uint8Array
|
||||
*/
|
||||
export function base64ToUint8Array(base64: string): Uint8Array {
|
||||
const binary = atob(base64);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) {
|
||||
bytes[i] = binary.charCodeAt(i);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转 Uint8Array
|
||||
*/
|
||||
export function stringToUint8Array(str: string): Uint8Array {
|
||||
const encoder = new TextEncoder();
|
||||
return encoder.encode(str);
|
||||
}
|
||||
|
||||
/**
|
||||
* Uint8Array 转字符串
|
||||
*/
|
||||
export function uint8ArrayToString(bytes: Uint8Array): string {
|
||||
const decoder = new TextDecoder();
|
||||
return decoder.decode(bytes);
|
||||
}
|
||||
10
pkg/crypto/client/utils/uuid.ts
Normal file
10
pkg/crypto/client/utils/uuid.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* 生成UUID v4
|
||||
*/
|
||||
export function generateUUID(): string {
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
||||
const r = (Math.random() * 16) | 0;
|
||||
const v = c === 'x' ? r : (r & 0x3) | 0x8;
|
||||
return v.toString(16);
|
||||
});
|
||||
}
|
||||
71
pkg/crypto/compress.go
Normal file
71
pkg/crypto/compress.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"io"
|
||||
)
|
||||
|
||||
// CompressEncryptor 压缩加密器
|
||||
type CompressEncryptor struct {
|
||||
baseEncryptor Encryptor
|
||||
}
|
||||
|
||||
func NewCompressEncryptor(encryptor Encryptor) *CompressEncryptor {
|
||||
return &CompressEncryptor{baseEncryptor: encryptor}
|
||||
}
|
||||
|
||||
// Encrypt 先压缩后加密
|
||||
func (c *CompressEncryptor) Encrypt(plaintext []byte) ([]byte, error) {
|
||||
// 1. 压缩
|
||||
compressed, err := c.compress(plaintext)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 2. 加密
|
||||
return c.baseEncryptor.Encrypt(compressed)
|
||||
}
|
||||
|
||||
// Decrypt 先解密后解压
|
||||
func (c *CompressEncryptor) Decrypt(ciphertext []byte) ([]byte, error) {
|
||||
// 1. 解密
|
||||
compressed, err := c.baseEncryptor.Decrypt(ciphertext)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 2. 解压
|
||||
return c.decompress(compressed)
|
||||
}
|
||||
|
||||
func (c *CompressEncryptor) Name() string {
|
||||
return "GZIP-" + c.baseEncryptor.Name()
|
||||
}
|
||||
|
||||
// compress 使用gzip压缩
|
||||
func (c *CompressEncryptor) compress(data []byte) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
writer := gzip.NewWriter(&buf)
|
||||
|
||||
if _, err := writer.Write(data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := writer.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// decompress 使用gzip解压
|
||||
func (c *CompressEncryptor) decompress(data []byte) ([]byte, error) {
|
||||
reader, err := gzip.NewReader(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = reader.Close() }()
|
||||
|
||||
return io.ReadAll(reader)
|
||||
}
|
||||
36
pkg/crypto/hmac.go
Normal file
36
pkg/crypto/hmac.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// HMACSigner HMAC签名器
|
||||
type HMACSigner struct {
|
||||
key []byte
|
||||
}
|
||||
|
||||
// NewHMACSigner 创建HMAC签名器
|
||||
func NewHMACSigner(key string) *HMACSigner {
|
||||
return &HMACSigner{key: []byte(key)}
|
||||
}
|
||||
|
||||
func (s *HMACSigner) Sign(data []byte) ([]byte, error) {
|
||||
h := hmac.New(sha256.New, s.key)
|
||||
h.Write(data)
|
||||
return h.Sum(nil), nil
|
||||
}
|
||||
|
||||
func (s *HMACSigner) Verify(data, signature []byte) error {
|
||||
expected, err := s.Sign(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hmac.Equal(expected, signature) {
|
||||
return fmt.Errorf("签名验证失败")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
22
pkg/crypto/interface.go
Normal file
22
pkg/crypto/interface.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package crypto
|
||||
|
||||
// Encryptor 加密器接口
|
||||
type Encryptor interface {
|
||||
// Encrypt 加密数据
|
||||
Encrypt(plaintext []byte) ([]byte, error)
|
||||
|
||||
// Decrypt 解密数据
|
||||
Decrypt(ciphertext []byte) ([]byte, error)
|
||||
|
||||
// Name 返回加密算法名称
|
||||
Name() string
|
||||
}
|
||||
|
||||
// Signer 签名器接口
|
||||
type Signer interface {
|
||||
// Sign 生成签名
|
||||
Sign(data []byte) ([]byte, error)
|
||||
|
||||
// Verify 验证签名
|
||||
Verify(data, signature []byte) error
|
||||
}
|
||||
83
pkg/crypto/rsa.go
Normal file
83
pkg/crypto/rsa.go
Normal file
@@ -0,0 +1,83 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// RSAEncryptor RSA加密器
|
||||
type RSAEncryptor struct {
|
||||
publicKey *rsa.PublicKey
|
||||
privateKey *rsa.PrivateKey
|
||||
}
|
||||
|
||||
// NewRSAEncryptor 创建RSA加密器
|
||||
func NewRSAEncryptor(publicKeyPEM, privateKeyPEM []byte) (*RSAEncryptor, error) {
|
||||
encryptor := &RSAEncryptor{}
|
||||
|
||||
if len(publicKeyPEM) > 0 {
|
||||
block, _ := pem.Decode(publicKeyPEM)
|
||||
if block == nil {
|
||||
return nil, fmt.Errorf("解析公钥失败")
|
||||
}
|
||||
|
||||
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析公钥失败: %w", err)
|
||||
}
|
||||
|
||||
var ok bool
|
||||
encryptor.publicKey, ok = pub.(*rsa.PublicKey)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("不是RSA公钥")
|
||||
}
|
||||
} else {
|
||||
return nil, fmt.Errorf("公钥未设置")
|
||||
}
|
||||
|
||||
if len(privateKeyPEM) > 0 {
|
||||
block, _ := pem.Decode(privateKeyPEM)
|
||||
if block == nil {
|
||||
return nil, fmt.Errorf("解析私钥失败")
|
||||
}
|
||||
|
||||
priv, err := x509.ParsePKCS8PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析私钥失败: %w", err)
|
||||
}
|
||||
|
||||
var ok bool
|
||||
encryptor.privateKey, ok = priv.(*rsa.PrivateKey)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("不是RSA私钥")
|
||||
}
|
||||
} else {
|
||||
return nil, fmt.Errorf("私钥未设置")
|
||||
}
|
||||
|
||||
return encryptor, nil
|
||||
}
|
||||
|
||||
func (e *RSAEncryptor) Encrypt(plaintext []byte) ([]byte, error) {
|
||||
if e.publicKey == nil {
|
||||
return nil, fmt.Errorf("公钥未设置")
|
||||
}
|
||||
|
||||
return rsa.EncryptOAEP(sha256.New(), rand.Reader, e.publicKey, plaintext, nil)
|
||||
}
|
||||
|
||||
func (e *RSAEncryptor) Decrypt(ciphertext []byte) ([]byte, error) {
|
||||
if e.privateKey == nil {
|
||||
return nil, fmt.Errorf("私钥未设置")
|
||||
}
|
||||
|
||||
return rsa.DecryptOAEP(sha256.New(), rand.Reader, e.privateKey, ciphertext, nil)
|
||||
}
|
||||
|
||||
func (e *RSAEncryptor) Name() string {
|
||||
return "RSA-OAEP-SHA256"
|
||||
}
|
||||
@@ -3,75 +3,262 @@ package database
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
"go.mongodb.org/mongo-driver/mongo/readpref"
|
||||
"time"
|
||||
)
|
||||
|
||||
var _ MongoDB = (*mongoDB)(nil)
|
||||
|
||||
// MongoDB MongoDB接口
|
||||
type MongoDB interface {
|
||||
i()
|
||||
// GetDB 获取数据库实例
|
||||
GetDB() *mongo.Database
|
||||
Close() error
|
||||
|
||||
// GetClient 获取客户端实例
|
||||
GetClient() *mongo.Client
|
||||
|
||||
// GetCollection 获取集合
|
||||
GetCollection(name string) *mongo.Collection
|
||||
|
||||
// Ping 检查连接
|
||||
Ping(ctx context.Context) error
|
||||
|
||||
// Close 关闭连接
|
||||
Close(ctx context.Context) error
|
||||
|
||||
// WithContext 创建带超时的上下文
|
||||
WithContext(ctx context.Context) (context.Context, context.CancelFunc)
|
||||
}
|
||||
|
||||
// MongoDBConfig MongoDB配置
|
||||
type MongoDBConfig struct {
|
||||
Addr string `yaml:"addr"`
|
||||
User string `yaml:"user"`
|
||||
Pass string `yaml:"pass"`
|
||||
Name string `yaml:"name"`
|
||||
Timeout time.Duration `yaml:"timeout"`
|
||||
// 地址,支持多个地址: "localhost:27017,localhost:27018"
|
||||
Addr string `yaml:"addr" json:"addr"`
|
||||
|
||||
// 用户名
|
||||
User string `yaml:"user" json:"user"`
|
||||
|
||||
// 密码
|
||||
Pass string `yaml:"pass" json:"pass"`
|
||||
|
||||
// 数据库名称
|
||||
Name string `yaml:"name" json:"name"`
|
||||
|
||||
// 连接超时(秒)
|
||||
Timeout time.Duration `yaml:"timeout" json:"timeout"`
|
||||
|
||||
// 最大连接池大小
|
||||
MaxPoolSize uint64 `yaml:"max_pool_size" json:"max_pool_size"`
|
||||
|
||||
// 最小连接池大小
|
||||
MinPoolSize uint64 `yaml:"min_pool_size" json:"min_pool_size"`
|
||||
|
||||
// 最大连接空闲时间(秒)
|
||||
MaxConnIdleTime time.Duration `yaml:"max_conn_idle_time" json:"max_conn_idle_time"`
|
||||
|
||||
// 是否使用副本集
|
||||
ReplicaSet string `yaml:"replica_set" json:"replica_set"`
|
||||
|
||||
// 是否使用TLS
|
||||
UseTLS bool `yaml:"use_tls" json:"use_tls"`
|
||||
|
||||
// 认证数据库
|
||||
AuthSource string `yaml:"auth_source" json:"auth_source"`
|
||||
}
|
||||
|
||||
// DefaultMongoDBConfig 默认配置
|
||||
func DefaultMongoDBConfig() *MongoDBConfig {
|
||||
return &MongoDBConfig{
|
||||
Timeout: 10, // 10秒
|
||||
MaxPoolSize: 100,
|
||||
MinPoolSize: 10,
|
||||
MaxConnIdleTime: 60, // 60秒
|
||||
AuthSource: "admin",
|
||||
}
|
||||
}
|
||||
|
||||
// mongoDB MongoDB实现
|
||||
type mongoDB struct {
|
||||
client *mongo.Client
|
||||
db *mongo.Database
|
||||
config *MongoDBConfig
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func (m *mongoDB) i() {}
|
||||
// NewMongoDB 创建MongoDB实例
|
||||
func NewMongoDB(cfg *MongoDBConfig) (MongoDB, error) {
|
||||
if cfg == nil {
|
||||
return nil, fmt.Errorf("配置不能为空")
|
||||
}
|
||||
|
||||
// 验证必填参数
|
||||
if cfg.Addr == "" {
|
||||
return nil, fmt.Errorf("地址不能为空")
|
||||
}
|
||||
if cfg.Name == "" {
|
||||
return nil, fmt.Errorf("数据库名称不能为空")
|
||||
}
|
||||
|
||||
func NewMongoDB(cfg MongoDBConfig) (MongoDB, error) {
|
||||
timeout := cfg.Timeout * time.Second
|
||||
connectCtx, connectCancelFunc := context.WithTimeout(context.Background(), timeout)
|
||||
defer connectCancelFunc()
|
||||
var auth string
|
||||
if len(cfg.User) > 0 && len(cfg.Pass) > 0 {
|
||||
auth = fmt.Sprintf("%s:%s@", cfg.User, cfg.Pass)
|
||||
}
|
||||
client, err := mongo.Connect(connectCtx, options.Client().ApplyURI(
|
||||
fmt.Sprintf("mongodb://%s%s", auth, cfg.Addr),
|
||||
))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if timeout == 0 {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
|
||||
pingCtx, pingCancelFunc := context.WithTimeout(context.Background(), timeout)
|
||||
defer pingCancelFunc()
|
||||
err = client.Ping(pingCtx, readpref.Primary())
|
||||
// 构建连接选项
|
||||
clientOpts := options.Client()
|
||||
|
||||
// 构建URI
|
||||
uri := buildMongoURI(cfg)
|
||||
clientOpts.ApplyURI(uri)
|
||||
|
||||
// 设置连接池
|
||||
if cfg.MaxPoolSize > 0 {
|
||||
clientOpts.SetMaxPoolSize(cfg.MaxPoolSize)
|
||||
}
|
||||
if cfg.MinPoolSize > 0 {
|
||||
clientOpts.SetMinPoolSize(cfg.MinPoolSize)
|
||||
}
|
||||
if cfg.MaxConnIdleTime > 0 {
|
||||
clientOpts.SetMaxConnIdleTime(cfg.MaxConnIdleTime * time.Second)
|
||||
}
|
||||
|
||||
// 设置超时
|
||||
clientOpts.SetConnectTimeout(timeout)
|
||||
clientOpts.SetServerSelectionTimeout(timeout)
|
||||
|
||||
// 连接MongoDB
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
client, err := mongo.Connect(ctx, clientOpts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("连接MongoDB失败: %w", err)
|
||||
}
|
||||
|
||||
// Ping测试连接
|
||||
pingCtx, pingCancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer pingCancel()
|
||||
|
||||
if err = client.Ping(pingCtx, readpref.Primary()); err != nil {
|
||||
_ = client.Disconnect(context.Background())
|
||||
return nil, fmt.Errorf("Ping MongoDB失败: %w", err)
|
||||
}
|
||||
|
||||
return &mongoDB{
|
||||
client: client,
|
||||
db: client.Database(cfg.Name),
|
||||
config: cfg,
|
||||
timeout: timeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetDB 获取数据库实例
|
||||
func (m *mongoDB) GetDB() *mongo.Database {
|
||||
return m.db
|
||||
}
|
||||
|
||||
func (m *mongoDB) Close() error {
|
||||
disconnectCtx, disconnectCancelFunc := context.WithTimeout(context.Background(), m.timeout)
|
||||
defer disconnectCancelFunc()
|
||||
err := m.client.Disconnect(disconnectCtx)
|
||||
// GetClient 获取客户端实例
|
||||
func (m *mongoDB) GetClient() *mongo.Client {
|
||||
return m.client
|
||||
}
|
||||
|
||||
// GetCollection 获取集合
|
||||
func (m *mongoDB) GetCollection(name string) *mongo.Collection {
|
||||
return m.db.Collection(name)
|
||||
}
|
||||
|
||||
// Ping 检查连接
|
||||
func (m *mongoDB) Ping(ctx context.Context) error {
|
||||
pingCtx, cancel := m.WithContext(ctx)
|
||||
defer cancel()
|
||||
|
||||
return m.client.Ping(pingCtx, readpref.Primary())
|
||||
}
|
||||
|
||||
// Close 关闭连接
|
||||
func (m *mongoDB) Close(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
disconnectCtx, cancel := context.WithTimeout(ctx, m.timeout)
|
||||
defer cancel()
|
||||
|
||||
if err := m.client.Disconnect(disconnectCtx); err != nil {
|
||||
return fmt.Errorf("断开MongoDB连接失败: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// WithContext 创建带超时的上下文
|
||||
func (m *mongoDB) WithContext(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
return context.WithTimeout(ctx, m.timeout)
|
||||
}
|
||||
|
||||
// buildMongoURI 构建MongoDB URI
|
||||
func buildMongoURI(cfg *MongoDBConfig) string {
|
||||
var auth string
|
||||
if cfg.User != "" && cfg.Pass != "" {
|
||||
auth = fmt.Sprintf("%s:%s@", cfg.User, cfg.Pass)
|
||||
}
|
||||
|
||||
uri := fmt.Sprintf("mongodb://%s%s/%s", auth, cfg.Addr, cfg.Name)
|
||||
|
||||
// 添加查询参数
|
||||
params := []string{}
|
||||
|
||||
if cfg.AuthSource != "" {
|
||||
params = append(params, fmt.Sprintf("authSource=%s", cfg.AuthSource))
|
||||
}
|
||||
|
||||
if cfg.ReplicaSet != "" {
|
||||
params = append(params, fmt.Sprintf("replicaSet=%s", cfg.ReplicaSet))
|
||||
}
|
||||
|
||||
if cfg.UseTLS {
|
||||
params = append(params, "tls=true")
|
||||
}
|
||||
|
||||
if len(params) > 0 {
|
||||
uri += "?"
|
||||
for i, param := range params {
|
||||
if i > 0 {
|
||||
uri += "&"
|
||||
}
|
||||
uri += param
|
||||
}
|
||||
}
|
||||
|
||||
return uri
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
|
||||
// EnsureIndexes 确保索引存在
|
||||
func EnsureIndexes(ctx context.Context, collection *mongo.Collection, indexes []mongo.IndexModel) error {
|
||||
if len(indexes) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
_, err := collection.Indexes().CreateMany(ctx, indexes)
|
||||
if err != nil {
|
||||
return err
|
||||
return fmt.Errorf("创建索引失败: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// DropIndexes 删除索引
|
||||
func DropIndexes(ctx context.Context, collection *mongo.Collection, indexNames []string) error {
|
||||
for _, name := range indexNames {
|
||||
if _, err := collection.Indexes().DropOne(ctx, name); err != nil {
|
||||
return fmt.Errorf("删除索引 %s 失败: %w", name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,247 +1,499 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitea.bvbej.com/bvbej/base-golang/pkg/time_parse"
|
||||
"gitea.bvbej.com/bvbej/base-golang/pkg/trace"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
"gorm.io/gorm/schema"
|
||||
"gorm.io/gorm/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
callBackBeforeName = "core:before"
|
||||
callBackAfterName = "core:after"
|
||||
startTime = "_start_time"
|
||||
traceCtxName = "_trace_ctx_name"
|
||||
)
|
||||
|
||||
var _ MysqlRepo = (*mysqlRepo)(nil)
|
||||
|
||||
// MysqlRepo MySQL接口
|
||||
type MysqlRepo interface {
|
||||
i()
|
||||
GetRead(options ...Option) *gorm.DB
|
||||
GetWrite(options ...Option) *gorm.DB
|
||||
// DB 获取数据库实例(自动选择读写)
|
||||
DB(ctx context.Context, forceWrite ...bool) *gorm.DB
|
||||
|
||||
// GetRead 获取读库
|
||||
GetRead() *gorm.DB
|
||||
|
||||
// GetWrite 获取写库
|
||||
GetWrite() *gorm.DB
|
||||
|
||||
// Transaction 执行事务
|
||||
Transaction(ctx context.Context, fc func(*gorm.DB) error) error
|
||||
|
||||
// Close 关闭连接
|
||||
Close() error
|
||||
|
||||
// Ping 检查连接
|
||||
Ping(ctx context.Context) error
|
||||
|
||||
// Stats 获取连接池统计信息
|
||||
Stats() (*DBStats, error)
|
||||
|
||||
// HealthCheck 健康检查
|
||||
HealthCheck(ctx context.Context) error
|
||||
}
|
||||
|
||||
// DBStats 数据库统计信息
|
||||
type DBStats struct {
|
||||
Read sql.DBStats `json:"read"`
|
||||
Write sql.DBStats `json:"write"`
|
||||
}
|
||||
|
||||
// MySQLConfig MySQL配置
|
||||
type MySQLConfig struct {
|
||||
Read struct {
|
||||
Addr string `yaml:"addr"`
|
||||
User string `yaml:"user"`
|
||||
Pass string `yaml:"pass"`
|
||||
Name string `yaml:"name"`
|
||||
} `yaml:"read"`
|
||||
Write struct {
|
||||
Addr string `yaml:"addr"`
|
||||
User string `yaml:"user"`
|
||||
Pass string `yaml:"pass"`
|
||||
Name string `yaml:"name"`
|
||||
} `yaml:"write"`
|
||||
Base struct {
|
||||
MaxOpenConn int `yaml:"maxOpenConn"` //最大连接数
|
||||
MaxIdleConn int `yaml:"maxIdleConn"` //最大空闲连接数
|
||||
ConnMaxLifeTime time.Duration `yaml:"connMaxLifeTime"` //最大连接超时(分钟)
|
||||
} `yaml:"base"`
|
||||
Read DBConnConfig `yaml:"read" json:"read"`
|
||||
Write DBConnConfig `yaml:"write" json:"write"`
|
||||
Base BaseConfig `yaml:"base" json:"base"`
|
||||
Logger LoggerConfig `yaml:"logger" json:"logger"`
|
||||
}
|
||||
|
||||
// DBConnConfig 数据库连接配置
|
||||
type DBConnConfig struct {
|
||||
Addr string `yaml:"addr" json:"addr"`
|
||||
User string `yaml:"user" json:"user"`
|
||||
Pass string `yaml:"pass" json:"pass"`
|
||||
Name string `yaml:"name" json:"name"`
|
||||
Charset string `yaml:"charset" json:"charset"` // 默认 utf8mb4
|
||||
Collation string `yaml:"collation" json:"collation"` // 默认 utf8mb4_unicode_ci
|
||||
Loc string `yaml:"loc" json:"loc"` // 默认 Local
|
||||
ParseTime bool `yaml:"parse_time" json:"parse_time"` // 默认 true
|
||||
Timeout time.Duration `yaml:"timeout" json:"timeout"` // 连接超时(秒)
|
||||
ReadTimeout time.Duration `yaml:"read_timeout" json:"read_timeout"` // 读超时(秒)
|
||||
WriteTimeout time.Duration `yaml:"write_timeout" json:"write_timeout"` // 写超时(秒)
|
||||
}
|
||||
|
||||
// BaseConfig 基础配置
|
||||
type BaseConfig struct {
|
||||
MaxOpenConn int `yaml:"max_open_conn" json:"max_open_conn"`
|
||||
MaxIdleConn int `yaml:"max_idle_conn" json:"max_idle_conn"`
|
||||
ConnMaxLifetime time.Duration `yaml:"conn_max_lifetime" json:"conn_max_lifetime"` // 秒
|
||||
ConnMaxIdleTime time.Duration `yaml:"conn_max_idle_time" json:"conn_max_idle_time"` // 秒
|
||||
}
|
||||
|
||||
// LoggerConfig 日志配置
|
||||
type LoggerConfig struct {
|
||||
SlowThreshold time.Duration `yaml:"slow_threshold" json:"slow_threshold"`
|
||||
Colorful bool `yaml:"colorful" json:"colorful"`
|
||||
IgnoreRecordNotFoundError bool `yaml:"ignore_record_not_found_error" json:"ignore_record_not_found_error"`
|
||||
LogLevel string `yaml:"log_level" json:"log_level"`
|
||||
LogOutput string `yaml:"log_output" json:"log_output"` // stdout, file
|
||||
LogFile string `yaml:"log_file" json:"log_file"` // 日志文件路径
|
||||
}
|
||||
|
||||
// DefaultMySQLConfig 默认配置
|
||||
func DefaultMySQLConfig() *MySQLConfig {
|
||||
return &MySQLConfig{
|
||||
Base: BaseConfig{
|
||||
MaxOpenConn: 100,
|
||||
MaxIdleConn: 10,
|
||||
ConnMaxLifetime: 3600, // 1小时
|
||||
ConnMaxIdleTime: 600, // 10分钟
|
||||
},
|
||||
Logger: LoggerConfig{
|
||||
SlowThreshold: 200 * time.Millisecond,
|
||||
Colorful: true,
|
||||
IgnoreRecordNotFoundError: true,
|
||||
LogLevel: "warn",
|
||||
LogOutput: "stdout",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// mysqlRepo MySQL实现
|
||||
type mysqlRepo struct {
|
||||
read *gorm.DB
|
||||
write *gorm.DB
|
||||
read *gorm.DB
|
||||
write *gorm.DB
|
||||
config *MySQLConfig
|
||||
mu sync.RWMutex
|
||||
closed bool
|
||||
}
|
||||
|
||||
func NewMysql(cfg MySQLConfig) (MysqlRepo, error) {
|
||||
dbr, err := dbConnect(cfg.Read.User, cfg.Read.Pass, cfg.Read.Addr, cfg.Read.Name,
|
||||
cfg.Base.MaxOpenConn, cfg.Base.MaxIdleConn, cfg.Base.ConnMaxLifeTime)
|
||||
if err != nil {
|
||||
// NewMysql 创建MySQL实例
|
||||
func NewMysql(cfg *MySQLConfig) (MysqlRepo, error) {
|
||||
if cfg == nil {
|
||||
cfg = DefaultMySQLConfig()
|
||||
}
|
||||
|
||||
// 合并默认配置
|
||||
mergeDefaultConfig(cfg)
|
||||
|
||||
// 验证配置
|
||||
if err := validateMySQLConfig(cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dbw, err := dbConnect(cfg.Write.User, cfg.Write.Pass, cfg.Write.Addr, cfg.Write.Name,
|
||||
cfg.Base.MaxOpenConn, cfg.Base.MaxIdleConn, cfg.Base.ConnMaxLifeTime)
|
||||
// 连接读库
|
||||
dbr, err := dbConnect("read", cfg.Read, cfg.Base, cfg.Logger)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("连接读库失败: %w", err)
|
||||
}
|
||||
|
||||
return &mysqlRepo{
|
||||
read: dbr,
|
||||
write: dbw,
|
||||
// 连接写库
|
||||
dbw, err := dbConnect("write", cfg.Write, cfg.Base, cfg.Logger)
|
||||
if err != nil {
|
||||
_ = closeDB(dbr)
|
||||
return nil, fmt.Errorf("连接写库失败: %w", err)
|
||||
}
|
||||
|
||||
repo := &mysqlRepo{
|
||||
read: dbr,
|
||||
write: dbw,
|
||||
config: cfg,
|
||||
closed: false,
|
||||
}
|
||||
|
||||
return repo, nil
|
||||
}
|
||||
|
||||
// DB 获取数据库实例(自动选择读写)
|
||||
func (m *mysqlRepo) DB(ctx context.Context, forceWrite ...bool) *gorm.DB {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
useWrite := len(forceWrite) > 0 && forceWrite[0]
|
||||
|
||||
var db *gorm.DB
|
||||
if useWrite {
|
||||
db = m.write
|
||||
} else {
|
||||
db = m.read
|
||||
}
|
||||
|
||||
if ctx != nil {
|
||||
db = db.WithContext(ctx)
|
||||
}
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
// GetRead 获取读库
|
||||
func (m *mysqlRepo) GetRead() *gorm.DB {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
return m.read
|
||||
}
|
||||
|
||||
// GetWrite 获取写库
|
||||
func (m *mysqlRepo) GetWrite() *gorm.DB {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
return m.write
|
||||
}
|
||||
|
||||
// Transaction 执行事务
|
||||
func (m *mysqlRepo) Transaction(ctx context.Context, fc func(*gorm.DB) error) error {
|
||||
m.mu.RLock()
|
||||
if m.closed {
|
||||
m.mu.RUnlock()
|
||||
return fmt.Errorf("数据库连接已关闭")
|
||||
}
|
||||
db := m.write
|
||||
m.mu.RUnlock()
|
||||
|
||||
if ctx != nil {
|
||||
db = db.WithContext(ctx)
|
||||
}
|
||||
|
||||
return db.Transaction(fc)
|
||||
}
|
||||
|
||||
// Close 关闭连接
|
||||
func (m *mysqlRepo) Close() error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if m.closed {
|
||||
return nil
|
||||
}
|
||||
|
||||
var errs []error
|
||||
if err := closeDB(m.read); err != nil {
|
||||
errs = append(errs, fmt.Errorf("关闭读库失败: %w", err))
|
||||
}
|
||||
if err := closeDB(m.write); err != nil {
|
||||
errs = append(errs, fmt.Errorf("关闭写库失败: %w", err))
|
||||
}
|
||||
|
||||
m.closed = true
|
||||
|
||||
if len(errs) > 0 {
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Ping 检查连接
|
||||
func (m *mysqlRepo) Ping(ctx context.Context) error {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
if m.closed {
|
||||
return fmt.Errorf("数据库连接已关闭")
|
||||
}
|
||||
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
// Ping读库
|
||||
readDB, err := m.read.DB()
|
||||
if err != nil {
|
||||
return fmt.Errorf("获取读库失败: %w", err)
|
||||
}
|
||||
if err := readDB.PingContext(ctx); err != nil {
|
||||
return fmt.Errorf("Ping读库失败: %w", err)
|
||||
}
|
||||
|
||||
// Ping写库
|
||||
writeDB, err := m.write.DB()
|
||||
if err != nil {
|
||||
return fmt.Errorf("获取写库失败: %w", err)
|
||||
}
|
||||
if err := writeDB.PingContext(ctx); err != nil {
|
||||
return fmt.Errorf("Ping写库失败: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stats 获取连接池统计信息
|
||||
func (m *mysqlRepo) Stats() (*DBStats, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
if m.closed {
|
||||
return nil, fmt.Errorf("数据库连接已关闭")
|
||||
}
|
||||
|
||||
readDB, err := m.read.DB()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取读库失败: %w", err)
|
||||
}
|
||||
|
||||
writeDB, err := m.write.DB()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取写库失败: %w", err)
|
||||
}
|
||||
|
||||
return &DBStats{
|
||||
Read: readDB.Stats(),
|
||||
Write: writeDB.Stats(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *mysqlRepo) i() {}
|
||||
|
||||
func (d *mysqlRepo) GetRead(options ...Option) *gorm.DB {
|
||||
opt := newOption()
|
||||
for _, f := range options {
|
||||
f(opt)
|
||||
// HealthCheck 健康检查
|
||||
func (m *mysqlRepo) HealthCheck(ctx context.Context) error {
|
||||
if err := m.Ping(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
db := d.read
|
||||
if opt.Trace != nil {
|
||||
db.InstanceSet(traceCtxName, opt.Trace)
|
||||
stats, err := m.Stats()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return db
|
||||
// 检查连接池状态
|
||||
if stats.Read.OpenConnections >= m.config.Base.MaxOpenConn {
|
||||
return fmt.Errorf("读库连接池已满")
|
||||
}
|
||||
if stats.Write.OpenConnections >= m.config.Base.MaxOpenConn {
|
||||
return fmt.Errorf("写库连接池已满")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *mysqlRepo) GetWrite(options ...Option) *gorm.DB {
|
||||
opt := newOption()
|
||||
for _, f := range options {
|
||||
f(opt)
|
||||
// mergeDefaultConfig 合并默认配置
|
||||
func mergeDefaultConfig(cfg *MySQLConfig) {
|
||||
// 读库默认配置
|
||||
if cfg.Read.Charset == "" {
|
||||
cfg.Read.Charset = "utf8mb4"
|
||||
}
|
||||
|
||||
db := d.write
|
||||
if opt.Trace != nil {
|
||||
db.InstanceSet(traceCtxName, opt.Trace)
|
||||
if cfg.Read.Collation == "" {
|
||||
cfg.Read.Collation = "utf8mb4_unicode_ci"
|
||||
}
|
||||
if cfg.Read.Loc == "" {
|
||||
cfg.Read.Loc = "Local"
|
||||
}
|
||||
if cfg.Read.Timeout == 0 {
|
||||
cfg.Read.Timeout = 10 // 10秒
|
||||
}
|
||||
if cfg.Read.ReadTimeout == 0 {
|
||||
cfg.Read.ReadTimeout = 30 // 30秒
|
||||
}
|
||||
if cfg.Read.WriteTimeout == 0 {
|
||||
cfg.Read.WriteTimeout = 30 // 30秒
|
||||
}
|
||||
cfg.Read.ParseTime = true
|
||||
|
||||
return db
|
||||
// 写库默认配置
|
||||
if cfg.Write.Charset == "" {
|
||||
cfg.Write.Charset = "utf8mb4"
|
||||
}
|
||||
if cfg.Write.Collation == "" {
|
||||
cfg.Write.Collation = "utf8mb4_unicode_ci"
|
||||
}
|
||||
if cfg.Write.Loc == "" {
|
||||
cfg.Write.Loc = "Local"
|
||||
}
|
||||
if cfg.Write.Timeout == 0 {
|
||||
cfg.Write.Timeout = 10
|
||||
}
|
||||
if cfg.Write.ReadTimeout == 0 {
|
||||
cfg.Write.ReadTimeout = 30
|
||||
}
|
||||
if cfg.Write.WriteTimeout == 0 {
|
||||
cfg.Write.WriteTimeout = 30
|
||||
}
|
||||
cfg.Write.ParseTime = true
|
||||
}
|
||||
|
||||
func (d *mysqlRepo) Close() (err error) {
|
||||
rdb, err1 := d.read.DB()
|
||||
if err1 != nil {
|
||||
err = errors.Join(err1)
|
||||
// validateMySQLConfig 验证配置
|
||||
func validateMySQLConfig(cfg *MySQLConfig) error {
|
||||
if cfg.Read.Addr == "" {
|
||||
return fmt.Errorf("读库地址不能为空")
|
||||
}
|
||||
err2 := rdb.Close()
|
||||
if err2 != nil {
|
||||
err = errors.Join(err2)
|
||||
if cfg.Read.User == "" {
|
||||
return fmt.Errorf("读库用户名不能为空")
|
||||
}
|
||||
if cfg.Read.Name == "" {
|
||||
return fmt.Errorf("读库数据库名不能为空")
|
||||
}
|
||||
|
||||
wdb, err3 := d.write.DB()
|
||||
if err3 != nil {
|
||||
err = errors.Join(err3)
|
||||
if cfg.Write.Addr == "" {
|
||||
return fmt.Errorf("写库地址不能为空")
|
||||
}
|
||||
err4 := wdb.Close()
|
||||
if err4 != nil {
|
||||
err = errors.Join(err4)
|
||||
if cfg.Write.User == "" {
|
||||
return fmt.Errorf("写库用户名不能为空")
|
||||
}
|
||||
if cfg.Write.Name == "" {
|
||||
return fmt.Errorf("写库数据库名不能为空")
|
||||
}
|
||||
|
||||
return err
|
||||
return nil
|
||||
}
|
||||
|
||||
func dbConnect(user, pass, addr, dbName string, maxOpenConn, maxIdleConn int, connMaxLifeTime time.Duration) (*gorm.DB, error) {
|
||||
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=%t&loc=%s",
|
||||
user,
|
||||
pass,
|
||||
addr,
|
||||
dbName,
|
||||
true,
|
||||
"Local")
|
||||
// buildDSN 构建DSN
|
||||
func buildDSN(conn DBConnConfig) string {
|
||||
return fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=%s&collation=%s&parseTime=%t&loc=%s&timeout=%ds&readTimeout=%ds&writeTimeout=%ds",
|
||||
conn.User,
|
||||
conn.Pass,
|
||||
conn.Addr,
|
||||
conn.Name,
|
||||
conn.Charset,
|
||||
conn.Collation,
|
||||
conn.ParseTime,
|
||||
conn.Loc,
|
||||
int(conn.Timeout),
|
||||
int(conn.ReadTimeout),
|
||||
int(conn.WriteTimeout),
|
||||
)
|
||||
}
|
||||
|
||||
// dbConnect 连接数据库
|
||||
func dbConnect(name string, conn DBConnConfig, base BaseConfig, logCfg LoggerConfig) (*gorm.DB, error) {
|
||||
// 构建DSN
|
||||
dsn := buildDSN(conn)
|
||||
|
||||
// 配置日志
|
||||
logLevel := parseLogLevel(logCfg.LogLevel)
|
||||
logWriter := getLogWriter(logCfg)
|
||||
|
||||
// 日志配置
|
||||
newLogger := logger.New(
|
||||
log.New(os.Stdout, "\r\n", log.LstdFlags),
|
||||
log.New(logWriter, "\r\n", log.LstdFlags),
|
||||
logger.Config{
|
||||
SlowThreshold: time.Second, // 慢SQL阈值
|
||||
Colorful: true, // 彩色打印
|
||||
IgnoreRecordNotFoundError: true, // 忽略记录未找到错误
|
||||
LogLevel: logger.Error, // 日志级别
|
||||
SlowThreshold: logCfg.SlowThreshold,
|
||||
Colorful: logCfg.Colorful,
|
||||
IgnoreRecordNotFoundError: logCfg.IgnoreRecordNotFoundError,
|
||||
LogLevel: logLevel,
|
||||
},
|
||||
)
|
||||
|
||||
// 打开数据库连接
|
||||
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
|
||||
NamingStrategy: schema.NamingStrategy{
|
||||
SingularTable: true,
|
||||
},
|
||||
Logger: newLogger,
|
||||
Logger: newLogger,
|
||||
SkipDefaultTransaction: true,
|
||||
PrepareStmt: true,
|
||||
DisableForeignKeyConstraintWhenMigrating: true,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, fmt.Errorf("[db connection failed] Database name: %s", dbName))
|
||||
return nil, fmt.Errorf("打开数据库连接失败 [%s]: %w", name, err)
|
||||
}
|
||||
|
||||
db.Set("gorm:table_options", "CHARSET=utf8mb4")
|
||||
|
||||
// 获取底层sqlDB
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("获取sqlDB失败: %w", err)
|
||||
}
|
||||
|
||||
// 设置连接池 用于设置最大打开的连接数,默认值为0表示不限制.设置最大的连接数,可以避免并发太高导致连接mysql出现too many connections的错误。
|
||||
sqlDB.SetMaxOpenConns(maxOpenConn)
|
||||
|
||||
// 设置最大连接数 用于设置闲置的连接数.设置闲置的连接数则当开启的一个连接使用完成后可以放在池里等候下一次使用。
|
||||
sqlDB.SetMaxIdleConns(maxIdleConn)
|
||||
|
||||
// 设置最大连接超时
|
||||
sqlDB.SetConnMaxLifetime(time.Minute * connMaxLifeTime)
|
||||
|
||||
// 使用插件
|
||||
err = db.Use(&TracePlugin{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
// 设置连接池参数
|
||||
if base.MaxOpenConn > 0 {
|
||||
sqlDB.SetMaxOpenConns(base.MaxOpenConn)
|
||||
}
|
||||
if base.MaxIdleConn > 0 {
|
||||
sqlDB.SetMaxIdleConns(base.MaxIdleConn)
|
||||
}
|
||||
if base.ConnMaxLifetime > 0 {
|
||||
sqlDB.SetConnMaxLifetime(base.ConnMaxLifetime * time.Second)
|
||||
}
|
||||
if base.ConnMaxIdleTime > 0 {
|
||||
sqlDB.SetConnMaxIdleTime(base.ConnMaxIdleTime * time.Second)
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
||||
/***************************************************************/
|
||||
|
||||
type TracePlugin struct{}
|
||||
|
||||
func (op *TracePlugin) Name() string {
|
||||
return "TracePlugin"
|
||||
// closeDB 关闭数据库
|
||||
func closeDB(db *gorm.DB) error {
|
||||
if db == nil {
|
||||
return nil
|
||||
}
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return sqlDB.Close()
|
||||
}
|
||||
|
||||
func (op *TracePlugin) Initialize(db *gorm.DB) (err error) {
|
||||
// 开始前
|
||||
_ = db.Callback().Create().Before("gorm:before_create").Register(callBackBeforeName, before)
|
||||
_ = db.Callback().Query().Before("gorm:query").Register(callBackBeforeName, before)
|
||||
_ = db.Callback().Delete().Before("gorm:before_delete").Register(callBackBeforeName, before)
|
||||
_ = db.Callback().Update().Before("gorm:setup_reflect_value").Register(callBackBeforeName, before)
|
||||
_ = db.Callback().Row().Before("gorm:row").Register(callBackBeforeName, before)
|
||||
_ = db.Callback().Raw().Before("gorm:raw").Register(callBackBeforeName, before)
|
||||
|
||||
// 结束后
|
||||
_ = db.Callback().Create().After("gorm:after_create").Register(callBackAfterName, after)
|
||||
_ = db.Callback().Query().After("gorm:after_query").Register(callBackAfterName, after)
|
||||
_ = db.Callback().Delete().After("gorm:after_delete").Register(callBackAfterName, after)
|
||||
_ = db.Callback().Update().After("gorm:after_update").Register(callBackAfterName, after)
|
||||
_ = db.Callback().Row().After("gorm:row").Register(callBackAfterName, after)
|
||||
_ = db.Callback().Raw().After("gorm:raw").Register(callBackAfterName, after)
|
||||
return
|
||||
// parseLogLevel 解析日志级别
|
||||
func parseLogLevel(level string) logger.LogLevel {
|
||||
switch level {
|
||||
case "silent":
|
||||
return logger.Silent
|
||||
case "error":
|
||||
return logger.Error
|
||||
case "warn":
|
||||
return logger.Warn
|
||||
case "info":
|
||||
return logger.Info
|
||||
default:
|
||||
return logger.Warn
|
||||
}
|
||||
}
|
||||
|
||||
func before(db *gorm.DB) {
|
||||
db.InstanceSet(startTime, time.Now())
|
||||
}
|
||||
|
||||
func after(db *gorm.DB) {
|
||||
_traceCtx, isExist := db.InstanceGet(traceCtxName)
|
||||
if !isExist {
|
||||
return
|
||||
}
|
||||
_trace, ok := _traceCtx.(trace.T)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
_ts, isExist := db.InstanceGet(startTime)
|
||||
if !isExist {
|
||||
return
|
||||
}
|
||||
|
||||
ts, ok := _ts.(time.Time)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
sql := db.Dialector.Explain(db.Statement.SQL.String(), db.Statement.Vars...)
|
||||
|
||||
sqlInfo := new(trace.SQL)
|
||||
sqlInfo.Timestamp = time_parse.CSTLayoutString()
|
||||
sqlInfo.SQL = sql
|
||||
sqlInfo.Stack = utils.FileWithLineNum()
|
||||
sqlInfo.Rows = db.Statement.RowsAffected
|
||||
sqlInfo.CostSeconds = time.Since(ts).Seconds()
|
||||
_trace.AppendSQL(sqlInfo)
|
||||
// getLogWriter 获取日志输出
|
||||
func getLogWriter(cfg LoggerConfig) *os.File {
|
||||
if cfg.LogOutput == "file" && cfg.LogFile != "" {
|
||||
file, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
|
||||
if err != nil {
|
||||
log.Printf("打开日志文件失败: %v,使用标准输出", err)
|
||||
return os.Stdout
|
||||
}
|
||||
return file
|
||||
}
|
||||
return os.Stdout
|
||||
}
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"gorm.io/gorm"
|
||||
"reflect"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type NullTime sql.NullTime
|
||||
@@ -50,6 +53,7 @@ type PaginateList struct {
|
||||
List any `json:"list"`
|
||||
}
|
||||
|
||||
// Paginate 分页查询
|
||||
func Paginate(db *gorm.DB, model any, page, size int64) (*PaginateList, error) {
|
||||
ptr := reflect.ValueOf(model)
|
||||
if ptr.Kind() != reflect.Ptr {
|
||||
@@ -86,3 +90,63 @@ func Paginate(db *gorm.DB, model any, page, size int64) (*PaginateList, error) {
|
||||
List: model,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// BatchInsert 批量插入
|
||||
func BatchInsert(ctx context.Context, db *gorm.DB, records interface{}, batchSize int) error {
|
||||
if batchSize <= 0 {
|
||||
batchSize = 100
|
||||
}
|
||||
|
||||
return db.WithContext(ctx).CreateInBatches(records, batchSize).Error
|
||||
}
|
||||
|
||||
// ExistsBy 检查记录是否存在
|
||||
func ExistsBy(ctx context.Context, db *gorm.DB, model interface{}, query interface{}, args ...interface{}) (bool, error) {
|
||||
var count int64
|
||||
err := db.WithContext(ctx).Model(model).Where(query, args...).Count(&count).Error
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
// FindByIDs 根据ID列表查询
|
||||
func FindByIDs(ctx context.Context, db *gorm.DB, dest interface{}, ids []uint) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
return db.WithContext(ctx).Where("id IN ?", ids).Find(dest).Error
|
||||
}
|
||||
|
||||
// SoftDeleteByIDs 批量软删除
|
||||
func SoftDeleteByIDs(ctx context.Context, db *gorm.DB, model interface{}, ids []uint) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
return db.WithContext(ctx).Where("id IN ?", ids).Delete(model).Error
|
||||
}
|
||||
|
||||
// UpdateFields 更新指定字段
|
||||
func UpdateFields(ctx context.Context, db *gorm.DB, model interface{}, id uint, fields map[string]interface{}) error {
|
||||
return db.WithContext(ctx).Model(model).Where("id = ?", id).Updates(fields).Error
|
||||
}
|
||||
|
||||
// Transaction 简化的事务助手
|
||||
func Transaction(ctx context.Context, db *gorm.DB, fn func(*gorm.DB) error) error {
|
||||
return db.WithContext(ctx).Transaction(fn)
|
||||
}
|
||||
|
||||
// BaseModel 基础模型
|
||||
type BaseModel struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`
|
||||
}
|
||||
|
||||
// SimpleModel 简单模型(无软删除)
|
||||
type SimpleModel struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
}
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
package database
|
||||
|
||||
import "gitea.bvbej.com/bvbej/base-golang/pkg/trace"
|
||||
|
||||
type Trace = trace.T
|
||||
|
||||
type Option func(*option)
|
||||
|
||||
func WithTrace(t Trace) Option {
|
||||
return func(opt *option) {
|
||||
if t != nil {
|
||||
opt.Trace = t.(*trace.Trace)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newOption() *option {
|
||||
return &option{}
|
||||
}
|
||||
|
||||
type option struct {
|
||||
Trace *trace.Trace
|
||||
}
|
||||
258
pkg/rsa/rsa.go
258
pkg/rsa/rsa.go
@@ -6,6 +6,7 @@ import (
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
)
|
||||
|
||||
var _ Public = (*rsaPub)(nil)
|
||||
@@ -19,7 +20,6 @@ type Public interface {
|
||||
|
||||
type Private interface {
|
||||
i()
|
||||
|
||||
Decrypt(decryptStr string) (string, error)
|
||||
DecryptURLEncoding(decryptStr string) (string, error)
|
||||
}
|
||||
@@ -46,86 +46,260 @@ func NewPrivate(privateKey string) Private {
|
||||
|
||||
func (pub *rsaPub) i() {}
|
||||
|
||||
func (pub *rsaPub) Encrypt(encryptStr string) (string, error) {
|
||||
// pem 解码
|
||||
block, _ := pem.Decode([]byte(pub.PublicKey))
|
||||
// parsePublicKey 解析多种格式的公钥
|
||||
func parsePublicKey(pemData []byte) (*rsa.PublicKey, error) {
|
||||
block, _ := pem.Decode(pemData)
|
||||
if block == nil {
|
||||
return nil, errors.New("failed to decode PEM block containing public key")
|
||||
}
|
||||
|
||||
// x509 解码
|
||||
publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||
// 检查PEM块类型
|
||||
switch block.Type {
|
||||
case "PUBLIC KEY": // PKIX/SPKI 格式 (Node.js生成的格式)
|
||||
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rsaPub, ok := pub.(*rsa.PublicKey); ok {
|
||||
return rsaPub, nil
|
||||
}
|
||||
return nil, errors.New("not an RSA public key")
|
||||
|
||||
case "RSA PUBLIC KEY": // PKCS#1 格式
|
||||
return x509.ParsePKCS1PublicKey(block.Bytes)
|
||||
|
||||
default:
|
||||
// 尝试自动检测格式
|
||||
// 先尝试PKIX格式
|
||||
if pub, err := x509.ParsePKIXPublicKey(block.Bytes); err == nil {
|
||||
if rsaPub, ok := pub.(*rsa.PublicKey); ok {
|
||||
return rsaPub, nil
|
||||
}
|
||||
}
|
||||
|
||||
// 再尝试PKCS#1格式
|
||||
if pub, err := x509.ParsePKCS1PublicKey(block.Bytes); err == nil {
|
||||
return pub, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("unsupported public key format: " + block.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func (pub *rsaPub) Encrypt(encryptStr string) (string, error) {
|
||||
publicKey, err := parsePublicKey([]byte(pub.PublicKey))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 类型断言
|
||||
publicKey := publicKeyInterface.(*rsa.PublicKey)
|
||||
|
||||
//对明文进行加密
|
||||
// 对明文进行加密
|
||||
encryptedStr, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, []byte(encryptStr))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
//返回密文
|
||||
// 返回密文
|
||||
return base64.StdEncoding.EncodeToString(encryptedStr), nil
|
||||
}
|
||||
|
||||
func (pub *rsaPub) EncryptURLEncoding(encryptStr string) (string, error) {
|
||||
// pem 解码
|
||||
block, _ := pem.Decode([]byte(pub.PublicKey))
|
||||
|
||||
// x509 解码
|
||||
publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||
publicKey, err := parsePublicKey([]byte(pub.PublicKey))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 类型断言
|
||||
publicKey := publicKeyInterface.(*rsa.PublicKey)
|
||||
|
||||
//对明文进行加密
|
||||
// 对明文进行加密
|
||||
encryptedStr, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, []byte(encryptStr))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
//返回密文
|
||||
// 返回密文
|
||||
return base64.URLEncoding.EncodeToString(encryptedStr), nil
|
||||
}
|
||||
|
||||
func (pri *rsaPri) i() {}
|
||||
|
||||
func (pri *rsaPri) Decrypt(decryptStr string) (string, error) {
|
||||
// pem 解码
|
||||
block, _ := pem.Decode([]byte(pri.PrivateKey))
|
||||
|
||||
// X509 解码
|
||||
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return "", err
|
||||
// parsePrivateKey 解析多种格式的私钥
|
||||
func parsePrivateKey(pemData []byte) (*rsa.PrivateKey, error) {
|
||||
block, _ := pem.Decode(pemData)
|
||||
if block == nil {
|
||||
return nil, errors.New("failed to decode PEM block containing private key")
|
||||
}
|
||||
decryptBytes, err := base64.StdEncoding.DecodeString(decryptStr)
|
||||
|
||||
//对密文进行解密
|
||||
decrypted, _ := rsa.DecryptPKCS1v15(rand.Reader, privateKey, decryptBytes)
|
||||
// 检查PEM块类型
|
||||
switch block.Type {
|
||||
case "RSA PRIVATE KEY": // PKCS#1 格式
|
||||
return x509.ParsePKCS1PrivateKey(block.Bytes)
|
||||
|
||||
//返回明文
|
||||
return string(decrypted), nil
|
||||
case "PRIVATE KEY": // PKCS#8 格式 (Node.js生成的格式)
|
||||
priv, err := x509.ParsePKCS8PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rsaPriv, ok := priv.(*rsa.PrivateKey); ok {
|
||||
return rsaPriv, nil
|
||||
}
|
||||
return nil, errors.New("not an RSA private key")
|
||||
|
||||
case "ENCRYPTED PRIVATE KEY": // 加密的PKCS#8格式
|
||||
// 注意:对于加密的PKCS#8私钥,需要先解密
|
||||
// 这里返回错误,建议用户先解密再使用
|
||||
return nil, errors.New("encrypted private key detected. Please decrypt it first before using")
|
||||
|
||||
default:
|
||||
// 尝试自动检测格式
|
||||
// 先尝试PKCS#1格式
|
||||
if priv, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil {
|
||||
return priv, nil
|
||||
}
|
||||
|
||||
// 再尝试PKCS#8格式
|
||||
if priv, err := x509.ParsePKCS8PrivateKey(block.Bytes); err == nil {
|
||||
if rsaPriv, ok := priv.(*rsa.PrivateKey); ok {
|
||||
return rsaPriv, nil
|
||||
}
|
||||
return nil, errors.New("not an RSA private key")
|
||||
}
|
||||
|
||||
return nil, errors.New("unsupported private key format: " + block.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func (pri *rsaPri) Decrypt(decryptStr string) (string, error) {
|
||||
return pri.decryptInternal(decryptStr, base64.StdEncoding.DecodeString)
|
||||
}
|
||||
|
||||
func (pri *rsaPri) DecryptURLEncoding(decryptStr string) (string, error) {
|
||||
// pem 解码
|
||||
block, _ := pem.Decode([]byte(pri.PrivateKey))
|
||||
return pri.decryptInternal(decryptStr, base64.URLEncoding.DecodeString)
|
||||
}
|
||||
|
||||
// X509 解码
|
||||
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
|
||||
// decryptInternal 内部解密方法
|
||||
func (pri *rsaPri) decryptInternal(
|
||||
decryptStr string,
|
||||
decodeFunc func(string) ([]byte, error),
|
||||
) (string, error) {
|
||||
// 解析私钥
|
||||
privateKey, err := parsePrivateKey([]byte(pri.PrivateKey))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
decryptBytes, err := base64.URLEncoding.DecodeString(decryptStr)
|
||||
|
||||
//对密文进行解密
|
||||
decrypted, _ := rsa.DecryptPKCS1v15(rand.Reader, privateKey, decryptBytes)
|
||||
// 解码Base64密文
|
||||
decryptBytes, err := decodeFunc(decryptStr)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
//返回明文
|
||||
// 对密文进行解密
|
||||
decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, decryptBytes)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 返回明文
|
||||
return string(decrypted), nil
|
||||
}
|
||||
|
||||
// DetectKeyFormat 辅助函数:检测密钥格式并提供使用建议
|
||||
func DetectKeyFormat(key string) (string, string, error) {
|
||||
block, _ := pem.Decode([]byte(key))
|
||||
if block == nil {
|
||||
return "", "", errors.New("invalid PEM format")
|
||||
}
|
||||
|
||||
var format string
|
||||
var suggestion string
|
||||
|
||||
switch block.Type {
|
||||
case "PUBLIC KEY":
|
||||
if _, err := x509.ParsePKIXPublicKey(block.Bytes); err == nil {
|
||||
format = "PKIX/SPKI Public Key"
|
||||
suggestion = "可以直接使用"
|
||||
} else {
|
||||
format = "Unknown Public Key"
|
||||
}
|
||||
|
||||
case "RSA PUBLIC KEY":
|
||||
format = "PKCS#1 Public Key"
|
||||
suggestion = "可以直接使用"
|
||||
|
||||
case "RSA PRIVATE KEY":
|
||||
format = "PKCS#1 Private Key"
|
||||
suggestion = "可以直接使用"
|
||||
|
||||
case "PRIVATE KEY":
|
||||
// 尝试解析以确认是否是PKCS#8
|
||||
if _, err := x509.ParsePKCS8PrivateKey(block.Bytes); err == nil {
|
||||
format = "PKCS#8 Private Key"
|
||||
suggestion = "可以直接使用(兼容Node.js生成的格式)"
|
||||
} else {
|
||||
format = "Unknown PKCS#8 Private Key"
|
||||
}
|
||||
|
||||
case "ENCRYPTED PRIVATE KEY":
|
||||
format = "Encrypted PKCS#8 Private Key"
|
||||
suggestion = "请先使用OpenSSL解密:openssl pkcs8 -in encrypted.pem -out decrypted.pem -nocrypt"
|
||||
|
||||
default:
|
||||
format = "Unknown Key Type: " + block.Type
|
||||
suggestion = "请转换为支持的格式"
|
||||
}
|
||||
|
||||
return format, suggestion, nil
|
||||
}
|
||||
|
||||
// ConvertPKCS8ToPKCS1 转换函数:PKCS#8 转 PKCS#1(如果需要)
|
||||
func ConvertPKCS8ToPKCS1(pkcs8Key string) (string, error) {
|
||||
block, _ := pem.Decode([]byte(pkcs8Key))
|
||||
if block == nil {
|
||||
return "", errors.New("failed to decode PEM block")
|
||||
}
|
||||
|
||||
if block.Type != "PRIVATE KEY" {
|
||||
return "", errors.New("not a PKCS#8 private key")
|
||||
}
|
||||
|
||||
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
rsaKey, ok := key.(*rsa.PrivateKey)
|
||||
if !ok {
|
||||
return "", errors.New("not an RSA private key")
|
||||
}
|
||||
|
||||
// 编码为 PKCS#1
|
||||
pkcs1Bytes := x509.MarshalPKCS1PrivateKey(rsaKey)
|
||||
pkcs1Block := &pem.Block{
|
||||
Type: "RSA PRIVATE KEY",
|
||||
Bytes: pkcs1Bytes,
|
||||
}
|
||||
|
||||
return string(pem.EncodeToMemory(pkcs1Block)), nil
|
||||
}
|
||||
|
||||
// IsEncryptedKey 检查是否是加密私钥
|
||||
func IsEncryptedKey(key string) bool {
|
||||
block, _ := pem.Decode([]byte(key))
|
||||
if block == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
// 现代加密私钥使用 ENCRYPTED PRIVATE KEY 类型
|
||||
return block.Type == "ENCRYPTED PRIVATE KEY"
|
||||
}
|
||||
|
||||
// DecryptPrivateKey 解密加密私钥的辅助函数(使用OpenSSL命令)
|
||||
func DecryptPrivateKey(encryptedKey, passphrase string) (string, error) {
|
||||
if !IsEncryptedKey(encryptedKey) {
|
||||
return "", errors.New("not an encrypted private key")
|
||||
}
|
||||
|
||||
// 注意:这里只提供建议,实际解密应在外部进行
|
||||
return "", errors.New(`请使用OpenSSL解密:
|
||||
openssl pkcs8 -in encrypted.pem -out decrypted.pem -passin pass:"` + passphrase + `"
|
||||
|
||||
或者使用编程方式在外部解密后再传入本库`)
|
||||
}
|
||||
|
||||
244
pkg/rsa/rsa.js
Normal file
244
pkg/rsa/rsa.js
Normal file
@@ -0,0 +1,244 @@
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
class KeyPairGenerator {
|
||||
constructor(options = {}) {
|
||||
this.options = {
|
||||
modulusLength: 2048, // 2048位在安全性和性能间取得平衡
|
||||
publicKeyEncoding: {
|
||||
type: 'spki',
|
||||
format: 'pem'
|
||||
},
|
||||
privateKeyEncoding: {
|
||||
type: 'pkcs8',
|
||||
format: 'pem',
|
||||
cipher: 'aes-256-cbc', // 可选加密私钥
|
||||
passphrase: options.passphrase || '' // 私钥密码
|
||||
},
|
||||
...options
|
||||
};
|
||||
}
|
||||
|
||||
// 生成密钥对
|
||||
generateKeyPair() {
|
||||
return new Promise((resolve, reject) => {
|
||||
crypto.generateKeyPair('rsa', this.options, (err, publicKey, privateKey) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
resolve({ publicKey, privateKey });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 保存密钥到文件
|
||||
saveKeyToFile(key, filename, directory = './keys') {
|
||||
if (!fs.existsSync(directory)) {
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
}
|
||||
|
||||
const filePath = path.join(directory, filename);
|
||||
fs.writeFileSync(filePath, key);
|
||||
console.log(`✅ ${filename} 已保存到: ${filePath}`);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
// 验证密钥对
|
||||
validateKeyPair(publicKey, privateKey, passphrase = '') {
|
||||
try {
|
||||
// 使用公钥加密测试数据
|
||||
const testData = 'test-signature-validation';
|
||||
const encrypted = crypto.publicEncrypt(publicKey, Buffer.from(testData));
|
||||
|
||||
// 使用私钥解密
|
||||
const decrypted = crypto.privateDecrypt(
|
||||
{ key: privateKey, passphrase },
|
||||
encrypted
|
||||
);
|
||||
|
||||
return decrypted.toString() === testData;
|
||||
} catch (error) {
|
||||
console.error('❌ 密钥对验证失败:', error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 生成完整的密钥对文件
|
||||
async generateAndSaveKeyPair(outputDir = './keys', keyName = 'app') {
|
||||
try {
|
||||
console.log('🔐 正在生成 RSA 密钥对...');
|
||||
|
||||
// 生成密钥对
|
||||
const { publicKey, privateKey } = await this.generateKeyPair();
|
||||
|
||||
// 验证密钥对
|
||||
console.log('🔍 验证密钥对...');
|
||||
const isValid = this.validateKeyPair(publicKey, privateKey, this.options.privateKeyEncoding.passphrase);
|
||||
|
||||
if (!isValid) {
|
||||
throw new Error('密钥对验证失败');
|
||||
}
|
||||
|
||||
console.log('✅ 密钥对验证成功');
|
||||
|
||||
// 保存文件
|
||||
const timestamp = new Date().toISOString().split('T')[0]+"-"+(new Date()).getTime();
|
||||
const publicKeyFile = this.saveKeyToFile(
|
||||
publicKey,
|
||||
`${keyName}-public-key-${timestamp}.pem`,
|
||||
outputDir
|
||||
);
|
||||
|
||||
const privateKeyFile = this.saveKeyToFile(
|
||||
privateKey,
|
||||
`${keyName}-private-key-${timestamp}.pem`,
|
||||
outputDir
|
||||
);
|
||||
|
||||
// 生成配置文件示例
|
||||
this.generateConfigExample(publicKey, privateKey, outputDir, keyName);
|
||||
|
||||
return {
|
||||
publicKey,
|
||||
privateKey,
|
||||
publicKeyFile,
|
||||
privateKeyFile,
|
||||
isValid
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 生成密钥对失败:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 生成配置文件示例
|
||||
generateConfigExample(publicKey, privateKey, outputDir, keyName) {
|
||||
const frontendConfig = `
|
||||
// 前端配置 (JavaScript/TypeScript)
|
||||
const RSA_PUBLIC_KEY = \`${publicKey}\`;
|
||||
|
||||
// 或者从文件导入
|
||||
// import publicKey from './${keyName}-public-key.pem';
|
||||
`;
|
||||
|
||||
const backendConfig = `
|
||||
// 后端配置 (Go)
|
||||
package config
|
||||
|
||||
const (
|
||||
RSAPrivateKey = \`${privateKey}\`
|
||||
)
|
||||
|
||||
// 或者从环境变量读取
|
||||
// privateKey := os.Getenv("RSA_PRIVATE_KEY")
|
||||
`;
|
||||
|
||||
const envExample = `
|
||||
# 环境变量示例
|
||||
RSA_PRIVATE_KEY="你的私钥内容"
|
||||
RSA_PUBLIC_KEY="你的公钥内容"
|
||||
KEY_PASSPHRASE="你的私钥密码(如果有)"
|
||||
`;
|
||||
|
||||
const timestamp = new Date().toISOString().split('T')[0]+"-"+(new Date()).getTime();
|
||||
this.saveKeyToFile(frontendConfig.trim(), 'frontend-config-example-'+timestamp+'.js', outputDir);
|
||||
this.saveKeyToFile(backendConfig.trim(), 'backend-config-example-'+timestamp+'.go', outputDir);
|
||||
this.saveKeyToFile(envExample.trim(), '.env.example', outputDir);
|
||||
|
||||
console.log('📝 配置文件示例已生成');
|
||||
}
|
||||
|
||||
// 显示密钥信息
|
||||
displayKeyInfo(publicKey, privateKey) {
|
||||
const publicKeyInfo = crypto.createPublicKey(publicKey);
|
||||
const privateKeyInfo = crypto.createPrivateKey({
|
||||
key: privateKey,
|
||||
passphrase: this.options.privateKeyEncoding.passphrase
|
||||
});
|
||||
|
||||
console.log('\n🔑 密钥信息:');
|
||||
console.log('──────────────────────────────');
|
||||
console.log(`算法: ${publicKeyInfo.asymmetricKeyType}`);
|
||||
console.log(`模数长度: ${publicKeyInfo.asymmetricKeySize} 位`);
|
||||
console.log(`格式: PEM`);
|
||||
|
||||
if (this.options.privateKeyEncoding.passphrase) {
|
||||
console.log(`私钥加密: ${this.options.privateKeyEncoding.cipher}`);
|
||||
} else {
|
||||
console.log('⚠️ 私钥未加密,建议在生产环境中使用加密私钥');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 命令行界面
|
||||
function main() {
|
||||
const args = process.argv.slice(2);
|
||||
const outputDir = args[0] || './keys';
|
||||
const keyName = args[1] || 'app';
|
||||
const useEncryption = args.includes('--encrypt');
|
||||
const passphrase = process.env.KEY_PASSPHRASE || '';
|
||||
|
||||
const generator = new KeyPairGenerator({
|
||||
privateKeyEncoding: {
|
||||
type: 'pkcs8',
|
||||
format: 'pem',
|
||||
...(useEncryption && {
|
||||
cipher: 'aes-256-cbc',
|
||||
passphrase: passphrase
|
||||
})
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`
|
||||
🔐 RSA 密钥对生成器
|
||||
──────────────────────────────
|
||||
输出目录: ${outputDir}
|
||||
密钥名称: ${keyName}
|
||||
私钥加密: ${useEncryption ? '是' : '否'}
|
||||
密钥长度: 2048 位 (平衡安全性与性能)
|
||||
`);
|
||||
|
||||
if (useEncryption && !passphrase) {
|
||||
console.log('❌ 请设置 KEY_PASSPHRASE 环境变量来加密私钥');
|
||||
console.log(' 例如: KEY_PASSPHRASE=your-secret-password node generate-keys.js');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
generator.generateAndSaveKeyPair(outputDir, keyName)
|
||||
.then((result) => {
|
||||
generator.displayKeyInfo(result.publicKey, result.privateKey);
|
||||
|
||||
console.log('\n🎉 密钥对生成完成!');
|
||||
console.log('──────────────────────────────');
|
||||
console.log('📁 生成的文件:');
|
||||
console.log(` 公钥: ${result.publicKeyFile}`);
|
||||
console.log(` 私钥: ${result.privateKeyFile}`);
|
||||
console.log(` 配置文件示例: ${outputDir}/`);
|
||||
|
||||
console.log('\n💡 使用建议:');
|
||||
console.log(' • 将公钥用于前端加密');
|
||||
console.log(' • 将私钥安全地存储在后端');
|
||||
console.log(' • 定期轮换密钥(建议每1-2年)');
|
||||
console.log(' • 不要将私钥提交到版本控制系统');
|
||||
|
||||
if (!useEncryption) {
|
||||
console.log('\n⚠️ 安全警告:');
|
||||
console.log(' 当前私钥未加密,建议在生产环境中使用加密私钥');
|
||||
console.log(' 重新运行并添加 --encrypt 参数和 KEY_PASSPHRASE 环境变量');
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('❌ 生成失败:', error.message);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
// 如果直接运行此文件
|
||||
if (require.main === module) {
|
||||
main();
|
||||
}
|
||||
|
||||
module.exports = KeyPairGenerator;
|
||||
Reference in New Issue
Block a user