Compare commits
12 Commits
8926ec889b
...
v0.13.3
| Author | SHA1 | Date | |
|---|---|---|---|
| 3b4b9952dc | |||
| 3005002379 | |||
| b3e319a21f | |||
| 078967c601 | |||
| 424ad78a7e | |||
| 5213f7002f | |||
| fe341735dd | |||
| 20f500ebcf | |||
| 9dc56ebe60 | |||
| fd13fafd86 | |||
| 4b82d3c44d | |||
| 795199a783 |
50
go.mod
50
go.mod
@@ -1,26 +1,26 @@
|
||||
module gitea.bvbej.com/bvbej/base-golang
|
||||
|
||||
go 1.25.1
|
||||
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.27.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.4
|
||||
github.com/redis/go-redis/v9 v9.14.0
|
||||
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
|
||||
@@ -28,21 +28,21 @@ require (
|
||||
github.com/tidwall/buntdb v1.3.2
|
||||
github.com/tidwall/gjson v1.18.0
|
||||
github.com/tus/tusd v1.13.0
|
||||
github.com/xuri/excelize/v2 v2.9.1
|
||||
go.mongodb.org/mongo-driver v1.17.4
|
||||
github.com/xuri/excelize/v2 v2.10.0
|
||||
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.0
|
||||
golang.org/x/crypto v0.42.0
|
||||
golang.org/x/net v0.44.0
|
||||
golang.org/x/sync v0.17.0
|
||||
golang.org/x/time v0.13.0
|
||||
google.golang.org/grpc v1.75.1
|
||||
google.golang.org/protobuf v1.36.9
|
||||
go.uber.org/zap v1.27.1
|
||||
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.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
|
||||
gorm.io/gorm v1.31.0
|
||||
gorm.io/gorm v1.31.1
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -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.8 // 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
|
||||
@@ -99,25 +99,25 @@ require (
|
||||
github.com/tidwall/pretty v1.2.0 // indirect
|
||||
github.com/tidwall/rtred v0.1.2 // indirect
|
||||
github.com/tidwall/tinyqueue v0.1.1 // indirect
|
||||
github.com/tiendc/go-deepcopy v1.6.0 // indirect
|
||||
github.com/tiendc/go-deepcopy v1.7.1 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.0 // indirect
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
|
||||
github.com/xdg-go/scram v1.1.2 // indirect
|
||||
github.com/xdg-go/stringprep v1.0.4 // indirect
|
||||
github.com/xuri/efp v0.0.1 // indirect
|
||||
github.com/xuri/nfp v0.0.1 // indirect
|
||||
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
|
||||
go.uber.org/mock v0.5.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
||||
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.27.0 // indirect
|
||||
golang.org/x/sys v0.36.0 // indirect
|
||||
golang.org/x/text v0.29.0 // indirect
|
||||
golang.org/x/tools v0.36.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7 // 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
|
||||
|
||||
120
go.sum
120
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.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
|
||||
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
|
||||
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.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4=
|
||||
github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
|
||||
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.4 h1:ulCKlTEyrZzmNytXweOrnva49+Q4+ASjYBCSXhkRWTo=
|
||||
github.com/qiniu/go-sdk/v7 v7.25.4/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.14.0 h1:u4tNCjXOyzfgeLN+vAZaW1xUooqWDqVEsZN0U01jfAE=
|
||||
github.com/redis/go-redis/v9 v9.14.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw=
|
||||
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=
|
||||
@@ -1357,8 +1357,8 @@ github.com/tidwall/rtred v0.1.2 h1:exmoQtOLvDoO8ud++6LwVsAMTu0KPzLTUrMln8u1yu8=
|
||||
github.com/tidwall/rtred v0.1.2/go.mod h1:hd69WNXQ5RP9vHd7dqekAz+RIdtfBogmglkZSRxCHFQ=
|
||||
github.com/tidwall/tinyqueue v0.1.1 h1:SpNEvEggbpyN5DIReaJ2/1ndroY8iyEGxPYxoSaymYE=
|
||||
github.com/tidwall/tinyqueue v0.1.1/go.mod h1:O/QNHwrnjqr6IHItYrzoHAKYhBkLI67Q096fQP5zMYw=
|
||||
github.com/tiendc/go-deepcopy v1.6.0 h1:0UtfV/imoCwlLxVsyfUd4hNHnB3drXsfle+wzSCA5Wo=
|
||||
github.com/tiendc/go-deepcopy v1.6.0/go.mod h1:toXoeQoUqXOOS/X4sKuiAoSk6elIdqc0pN7MTgOOo2I=
|
||||
github.com/tiendc/go-deepcopy v1.7.1 h1:LnubftI6nYaaMOcaz0LphzwraqN8jiWTwm416sitff4=
|
||||
github.com/tiendc/go-deepcopy v1.7.1/go.mod h1:4bKjNC2r7boYOkD2IOuZpYjmlDdzjbpTRyCx+goBCJQ=
|
||||
github.com/tus/tusd v1.13.0 h1:W7rtb1XPSpde/GPZAgdfUS3vus2Jt2KmckS6OUd3CU8=
|
||||
github.com/tus/tusd v1.13.0/go.mod h1:1tX4CDGlx8koHGFJdSaJ5ybUIm2NeVloJgZEPSKRcQA=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
@@ -1375,10 +1375,10 @@ github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gi
|
||||
github.com/xhit/go-str2duration v1.2.0/go.mod h1:3cPSlfZlUHVlneIVfePFWcJZsuwf+P1v2SRTV4cUmp4=
|
||||
github.com/xuri/efp v0.0.1 h1:fws5Rv3myXyYni8uwj2qKjVaRP30PdjeYe2Y6FDsCL8=
|
||||
github.com/xuri/efp v0.0.1/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=
|
||||
github.com/xuri/excelize/v2 v2.9.1 h1:VdSGk+rraGmgLHGFaGG9/9IWu1nj4ufjJ7uwMDtj8Qw=
|
||||
github.com/xuri/excelize/v2 v2.9.1/go.mod h1:x7L6pKz2dvo9ejrRuD8Lnl98z4JLt0TGAwjhW+EiP8s=
|
||||
github.com/xuri/nfp v0.0.1 h1:MDamSGatIvp8uOmDP8FnmjuQpu90NzdJxo7242ANR9Q=
|
||||
github.com/xuri/nfp v0.0.1/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
|
||||
github.com/xuri/excelize/v2 v2.10.0 h1:8aKsP7JD39iKLc6dH5Tw3dgV3sPRh8uRVXu/fMstfW4=
|
||||
github.com/xuri/excelize/v2 v2.10.0/go.mod h1:SC5TzhQkaOsTWpANfm+7bJCldzcnU/jrhqkTi/iBHBU=
|
||||
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 h1:+C0TIdyyYmzadGaL/HBLbf3WdLgC29pgyhTjAT/0nuE=
|
||||
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM=
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI=
|
||||
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
@@ -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.4 h1:jUorfmVzljjr0FLzYQsGP8cgN/qzzxlY9Vh0C9KFXVw=
|
||||
go.mongodb.org/mongo-driver v1.17.4/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=
|
||||
@@ -1403,18 +1403,18 @@ go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
|
||||
go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk=
|
||||
go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E=
|
||||
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
|
||||
go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ=
|
||||
go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I=
|
||||
go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE=
|
||||
go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E=
|
||||
go.opentelemetry.io/otel/sdk v1.37.0 h1:ItB0QUqnjesGRvNcmAcU0LyvkVyGJ2xftD29bWdDvKI=
|
||||
go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.37.0 h1:90lI228XrB9jCMuSdA0673aubgRobVZFhbjxHHspCPc=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.37.0/go.mod h1:cNen4ZWfiD37l5NhS+Keb5RXVWZWpRE+9WyVCpbo5ps=
|
||||
go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4=
|
||||
go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8=
|
||||
go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=
|
||||
go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA=
|
||||
go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA=
|
||||
go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
|
||||
go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
|
||||
go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI=
|
||||
go.opentelemetry.io/proto/otlp v0.15.0/go.mod h1:H7XAot3MsfNsj7EXtrA2q5xSNQ10UqI405h3+duxN4U=
|
||||
go.opentelemetry.io/proto/otlp v0.19.0/go.mod h1:H7XAot3MsfNsj7EXtrA2q5xSNQ10UqI405h3+duxN4U=
|
||||
@@ -1431,8 +1431,8 @@ go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo=
|
||||
go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI=
|
||||
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
|
||||
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
|
||||
go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
|
||||
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
@@ -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.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
|
||||
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
|
||||
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.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ=
|
||||
golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc=
|
||||
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.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I=
|
||||
golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY=
|
||||
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=
|
||||
@@ -1656,8 +1656,8 @@ golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
@@ -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.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
|
||||
golang.org/x/sys v0.36.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,16 +1801,16 @@ 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.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
||||
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
||||
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=
|
||||
golang.org/x/time v0.0.0-20220922220347-f3bd1da661af/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.1.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.13.0 h1:eUlYslOIt32DgYD6utsuUeHs4d7AsEYLuIAdg7FlYgI=
|
||||
golang.org/x/time v0.13.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
||||
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
|
||||
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
||||
golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
@@ -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.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
|
||||
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
|
||||
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-20250707201910-8d1bb00bc6a7 h1:pFyd6EwwL2TqFf8emdthzeX+gZE1ElRq3iM8pui4KBY=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A=
|
||||
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.75.1 h1:/ODCNEuf9VghjgO3rqLcfg8fiOP0nSluljWFlDxELLI=
|
||||
google.golang.org/grpc v1.75.1/go.mod h1:JtPAzKiq4v1xcAB2hydNlWI2RnF85XXcV0mhKXr2ecQ=
|
||||
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.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw=
|
||||
google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
|
||||
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=
|
||||
@@ -2234,8 +2234,8 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg=
|
||||
gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo=
|
||||
gorm.io/gorm v1.31.0 h1:0VlycGreVhK7RF/Bwt51Fk8v0xLiiiFdbGDPIZQ7mJY=
|
||||
gorm.io/gorm v1.31.0/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
||||
gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
|
||||
gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
|
||||
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"
|
||||
}
|
||||
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;
|
||||
@@ -5,6 +5,12 @@ import (
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitea.bvbej.com/bvbej/base-golang/pkg/color"
|
||||
"gitea.bvbej.com/bvbej/base-golang/pkg/ticker"
|
||||
"gitea.bvbej.com/bvbej/base-golang/pkg/token"
|
||||
@@ -12,11 +18,7 @@ import (
|
||||
"github.com/tus/tusd/pkg/filestore"
|
||||
tus "github.com/tus/tusd/pkg/handler"
|
||||
"go.uber.org/zap"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
var _ Server = (*server)(nil)
|
||||
@@ -36,6 +38,7 @@ type server struct {
|
||||
token token.Token
|
||||
store filestore.FileStore
|
||||
logger *zap.Logger
|
||||
logLevel zapcore.Level
|
||||
httpServer *http.Server
|
||||
ctx context.Context
|
||||
done context.CancelFunc
|
||||
@@ -52,13 +55,14 @@ type Config struct {
|
||||
Debug bool
|
||||
}
|
||||
|
||||
func New(conf Config, logger *zap.Logger) Server {
|
||||
func New(conf Config, logger *zap.Logger, logLevel zapcore.Level) Server {
|
||||
ctx, cancelFunc := context.WithCancel(context.Background())
|
||||
return &server{
|
||||
config: conf,
|
||||
uploading: sync.Map{},
|
||||
headerTokenKey: "Authorization",
|
||||
logger: logger,
|
||||
logLevel: logLevel,
|
||||
token: token.New(conf.Secret),
|
||||
ctx: ctx,
|
||||
done: cancelFunc,
|
||||
@@ -93,10 +97,11 @@ func (s *server) Start(completedEvent func(sha256, param string, info tus.FileIn
|
||||
s.store = filestore.New(s.config.Dir)
|
||||
s.store.UseIn(composer)
|
||||
|
||||
newLogger, _ := zap.NewStdLogAt(s.logger, s.logLevel)
|
||||
handler, err := tus.NewHandler(tus.Config{
|
||||
StoreComposer: composer,
|
||||
BasePath: s.config.Path,
|
||||
Logger: zap.NewStdLog(s.logger),
|
||||
Logger: newLogger,
|
||||
NotifyCompleteUploads: true,
|
||||
NotifyTerminatedUploads: true,
|
||||
DisableTermination: true,
|
||||
|
||||
Reference in New Issue
Block a user