mirror of
https://gitee.com/godoos/godoos.git
synced 2026-11-20 07:49:34 +08:00
add base
This commit is contained in:
Generated
-285
@@ -11,21 +11,6 @@ importers:
|
||||
'@element-plus/icons-vue':
|
||||
specifier: ^2.1.0
|
||||
version: 2.3.1(vue@3.5.13(typescript@5.6.3))
|
||||
'@tauri-apps/api':
|
||||
specifier: ^2
|
||||
version: 2.5.0
|
||||
'@tauri-apps/plugin-fs':
|
||||
specifier: ~2
|
||||
version: 2.2.1
|
||||
'@tauri-apps/plugin-opener':
|
||||
specifier: ^2
|
||||
version: 2.2.6
|
||||
'@tauri-apps/plugin-os':
|
||||
specifier: ~2
|
||||
version: 2.2.1
|
||||
'@tauri-apps/plugin-sql':
|
||||
specifier: ^2.2.0
|
||||
version: 2.2.0
|
||||
axios:
|
||||
specifier: ^1.7.9
|
||||
version: 1.9.0
|
||||
@@ -78,9 +63,6 @@ importers:
|
||||
specifier: ^3.3.1
|
||||
version: 3.3.1(vue@3.5.13(typescript@5.6.3))
|
||||
devDependencies:
|
||||
'@tauri-apps/cli':
|
||||
specifier: ^2
|
||||
version: 2.5.0
|
||||
'@types/file-saver':
|
||||
specifier: ^2.0.7
|
||||
version: 2.0.7
|
||||
@@ -108,9 +90,6 @@ importers:
|
||||
vite:
|
||||
specifier: ^6.0.3
|
||||
version: 6.3.4(@types/node@22.15.3)(jiti@2.4.2)(sass@1.87.0)
|
||||
vue-tsc:
|
||||
specifier: ^2.1.10
|
||||
version: 2.2.10(typescript@5.6.3)
|
||||
|
||||
packages:
|
||||
|
||||
@@ -544,92 +523,6 @@ packages:
|
||||
'@sxzz/popperjs-es@2.11.7':
|
||||
resolution: {integrity: sha512-Ccy0NlLkzr0Ex2FKvh2X+OyERHXJ88XJ1MXtsI9y9fGexlaXaVTPzBCRBwIxFkORuOb+uBqeu+RqnpgYTEZRUQ==}
|
||||
|
||||
'@tauri-apps/api@2.5.0':
|
||||
resolution: {integrity: sha512-Ldux4ip+HGAcPUmuLT8EIkk6yafl5vK0P0c0byzAKzxJh7vxelVtdPONjfgTm96PbN24yjZNESY8CKo8qniluA==}
|
||||
|
||||
'@tauri-apps/cli-darwin-arm64@2.5.0':
|
||||
resolution: {integrity: sha512-VuVAeTFq86dfpoBDNYAdtQVLbP0+2EKCHIIhkaxjeoPARR0sLpFHz2zs0PcFU76e+KAaxtEtAJAXGNUc8E1PzQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@tauri-apps/cli-darwin-x64@2.5.0':
|
||||
resolution: {integrity: sha512-hUF01sC06cZVa8+I0/VtsHOk9BbO75rd+YdtHJ48xTdcYaQ5QIwL4yZz9OR1AKBTaUYhBam8UX9Pvd5V2/4Dpw==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@tauri-apps/cli-linux-arm-gnueabihf@2.5.0':
|
||||
resolution: {integrity: sha512-LQKqttsK252LlqYyX8R02MinUsfFcy3+NZiJwHFgi5Y3+ZUIAED9cSxJkyNtuY5KMnR4RlpgWyLv4P6akN1xhg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-linux-arm64-gnu@2.5.0':
|
||||
resolution: {integrity: sha512-mTQufsPcpdHg5RW0zypazMo4L55EfeE5snTzrPqbLX4yCK2qalN7+rnP8O8GT06xhp6ElSP/Ku1M2MR297SByQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-linux-arm64-musl@2.5.0':
|
||||
resolution: {integrity: sha512-rQO1HhRUQqyEaal5dUVOQruTRda/TD36s9kv1hTxZiFuSq3558lsTjAcUEnMAtBcBkps20sbyTJNMT0AwYIk8Q==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-linux-riscv64-gnu@2.5.0':
|
||||
resolution: {integrity: sha512-7oS18FN46yDxyw1zX/AxhLAd7T3GrLj3Ai6s8hZKd9qFVzrAn36ESL7d3G05s8wEtsJf26qjXnVF4qleS3dYsA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-linux-x64-gnu@2.5.0':
|
||||
resolution: {integrity: sha512-SG5sFNL7VMmDBdIg3nO3EzNRT306HsiEQ0N90ILe3ZABYAVoPDO/ttpCO37ApLInTzrq/DLN+gOlC/mgZvLw1w==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-linux-x64-musl@2.5.0':
|
||||
resolution: {integrity: sha512-QXDM8zp/6v05PNWju5ELsVwF0VH1n6b5pk2E6W/jFbbiwz80Vs1lACl9pv5kEHkrxBj+aWU/03JzGuIj2g3SkQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-win32-arm64-msvc@2.5.0':
|
||||
resolution: {integrity: sha512-pFSHFK6b+o9y4Un8w0gGLwVyFTZaC3P0kQ7umRt/BLDkzD5RnQ4vBM7CF8BCU5nkwmEBUCZd7Wt3TWZxe41o6Q==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@tauri-apps/cli-win32-ia32-msvc@2.5.0':
|
||||
resolution: {integrity: sha512-EArv1IaRlogdLAQyGlKmEqZqm5RfHCUMhJoedWu7GtdbOMUfSAz6FMX2boE1PtEmNO4An+g188flLeVErrxEKg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [ia32]
|
||||
os: [win32]
|
||||
|
||||
'@tauri-apps/cli-win32-x64-msvc@2.5.0':
|
||||
resolution: {integrity: sha512-lj43EFYbnAta8pd9JnUq87o+xRUR0odz+4rixBtTUwUgdRdwQ2V9CzFtsMu6FQKpFQ6mujRK6P1IEwhL6ADRsQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@tauri-apps/cli@2.5.0':
|
||||
resolution: {integrity: sha512-rAtHqG0Gh/IWLjN2zTf3nZqYqbo81oMbqop56rGTjrlWk9pTTAjkqOjSL9XQLIMZ3RbeVjveCqqCA0s8RnLdMg==}
|
||||
engines: {node: '>= 10'}
|
||||
hasBin: true
|
||||
|
||||
'@tauri-apps/plugin-fs@2.2.1':
|
||||
resolution: {integrity: sha512-KdGzvvA4Eg0Dhw55MwczFbjxLxsTx0FvwwC/0StXlr6IxwPUxh5ziZQoaugkBFs8t+wfebdQrjBEzd8NmmDXNw==}
|
||||
|
||||
'@tauri-apps/plugin-opener@2.2.6':
|
||||
resolution: {integrity: sha512-bSdkuP71ZQRepPOn8BOEdBKYJQvl6+jb160QtJX/i2H9BF6ZySY/kYljh76N2Ne5fJMQRge7rlKoStYQY5Jq1w==}
|
||||
|
||||
'@tauri-apps/plugin-os@2.2.1':
|
||||
resolution: {integrity: sha512-cNYpNri2CCc6BaNeB6G/mOtLvg8dFyFQyCUdf2y0K8PIAKGEWdEcu8DECkydU2B+oj4OJihDPD2de5K6cbVl9A==}
|
||||
|
||||
'@tauri-apps/plugin-sql@2.2.0':
|
||||
resolution: {integrity: sha512-yGdybpaMENe/p6lTXslvDHYNNvD9qB7palaBBF5fJHdYSkwd3vrLiYU9dFfLwUAwnsBylND55EiivWsjhazejA==}
|
||||
|
||||
'@tootallnate/once@2.0.0':
|
||||
resolution: {integrity: sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==}
|
||||
engines: {node: '>= 10'}
|
||||
@@ -757,15 +650,6 @@ packages:
|
||||
vite: ^5.0.0 || ^6.0.0
|
||||
vue: ^3.2.25
|
||||
|
||||
'@volar/language-core@2.4.13':
|
||||
resolution: {integrity: sha512-MnQJ7eKchJx5Oz+YdbqyFUk8BN6jasdJv31n/7r6/WwlOOv7qzvot6B66887l2ST3bUW4Mewml54euzpJWA6bg==}
|
||||
|
||||
'@volar/source-map@2.4.13':
|
||||
resolution: {integrity: sha512-l/EBcc2FkvHgz2ZxV+OZK3kMSroMr7nN3sZLF2/f6kWW66q8+tEL4giiYyFjt0BcubqJhBt6soYIrAPhg/Yr+Q==}
|
||||
|
||||
'@volar/typescript@2.4.13':
|
||||
resolution: {integrity: sha512-Ukz4xv84swJPupZeoFsQoeJEOm7U9pqsEnaGGgt5ni3SCTa22m8oJP5Nng3Wed7Uw5RBELdLxxORX8YhJPyOgQ==}
|
||||
|
||||
'@vue/compiler-core@3.5.13':
|
||||
resolution: {integrity: sha512-oOdAkwqUfW1WqpwSYJce06wvt6HljgY3fGeM9NcVA1HaYOij3mZG9Rkysn0OHuyUAGMbEbARIpsG+LPVlBJ5/Q==}
|
||||
|
||||
@@ -778,20 +662,9 @@ packages:
|
||||
'@vue/compiler-ssr@3.5.13':
|
||||
resolution: {integrity: sha512-wMH6vrYHxQl/IybKJagqbquvxpWCuVYpoUJfCqFZwa/JY1GdATAQ+TgVtgrwwMZ0D07QhA99rs/EAAWfvG6KpA==}
|
||||
|
||||
'@vue/compiler-vue2@2.7.16':
|
||||
resolution: {integrity: sha512-qYC3Psj9S/mfu9uVi5WvNZIzq+xnXMhOwbTFKKDD7b1lhpnn71jXSFdTQ+WsIEk0ONCd7VV2IMm7ONl6tbQ86A==}
|
||||
|
||||
'@vue/devtools-api@6.6.4':
|
||||
resolution: {integrity: sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==}
|
||||
|
||||
'@vue/language-core@2.2.10':
|
||||
resolution: {integrity: sha512-+yNoYx6XIKuAO8Mqh1vGytu8jkFEOH5C8iOv3i8Z/65A7x9iAOXA97Q+PqZ3nlm2lxf5rOJuIGI/wDtx/riNYw==}
|
||||
peerDependencies:
|
||||
typescript: '*'
|
||||
peerDependenciesMeta:
|
||||
typescript:
|
||||
optional: true
|
||||
|
||||
'@vue/reactivity@3.5.13':
|
||||
resolution: {integrity: sha512-NaCwtw8o48B9I6L1zl2p41OHo/2Z4wqYGGIK1Khu5T7yxrn+ATOixn/Udn2m+6kZKB/J7cuT9DbWWhRxqixACg==}
|
||||
|
||||
@@ -843,9 +716,6 @@ packages:
|
||||
resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==}
|
||||
engines: {node: '>= 6.0.0'}
|
||||
|
||||
alien-signals@1.0.13:
|
||||
resolution: {integrity: sha512-OGj9yyTnJEttvzhTUWuscOvtqxq5vrhF7vL9oS0xJ2mK0ItPYP1/y+vCFebfxoEyAz0++1AIwJ5CMr+Fk3nDmg==}
|
||||
|
||||
anymatch@3.1.3:
|
||||
resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==}
|
||||
engines: {node: '>= 8'}
|
||||
@@ -859,9 +729,6 @@ packages:
|
||||
axios@1.9.0:
|
||||
resolution: {integrity: sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==}
|
||||
|
||||
balanced-match@1.0.2:
|
||||
resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
|
||||
|
||||
base64-arraybuffer@1.0.2:
|
||||
resolution: {integrity: sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==}
|
||||
engines: {node: '>= 0.6.0'}
|
||||
@@ -870,9 +737,6 @@ packages:
|
||||
resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
brace-expansion@2.0.1:
|
||||
resolution: {integrity: sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==}
|
||||
|
||||
braces@3.0.3:
|
||||
resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}
|
||||
engines: {node: '>=8'}
|
||||
@@ -1115,9 +979,6 @@ packages:
|
||||
dayjs@1.11.13:
|
||||
resolution: {integrity: sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==}
|
||||
|
||||
de-indent@1.0.2:
|
||||
resolution: {integrity: sha512-e/1zu3xH5MQryN2zdVaF0OrdNLUbvWxzMbi+iNA6Bky7l1RoP8a2fIbRocyHclXt/arDrrR6lL3TqFD9pMQTsg==}
|
||||
|
||||
debug@4.4.0:
|
||||
resolution: {integrity: sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==}
|
||||
engines: {node: '>=6.0'}
|
||||
@@ -1322,10 +1183,6 @@ packages:
|
||||
resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
he@1.2.0:
|
||||
resolution: {integrity: sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==}
|
||||
hasBin: true
|
||||
|
||||
html-encoding-sniffer@3.0.0:
|
||||
resolution: {integrity: sha512-oWv4T4yJ52iKrufjnyZPkrN0CH3QnrUqdB6In1g5Fe1mia8GmF36gnfNySxoZtxD5+NmYw1EElVXiBk93UeskA==}
|
||||
engines: {node: '>=12'}
|
||||
@@ -1465,10 +1322,6 @@ packages:
|
||||
resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==}
|
||||
engines: {node: '>= 0.6'}
|
||||
|
||||
minimatch@9.0.5:
|
||||
resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==}
|
||||
engines: {node: '>=16 || 14 >=14.17'}
|
||||
|
||||
mitt@3.0.1:
|
||||
resolution: {integrity: sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==}
|
||||
|
||||
@@ -1485,9 +1338,6 @@ packages:
|
||||
ms@2.1.3:
|
||||
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
|
||||
|
||||
muggle-string@0.4.1:
|
||||
resolution: {integrity: sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==}
|
||||
|
||||
nanoid@3.3.11:
|
||||
resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==}
|
||||
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
||||
@@ -1529,9 +1379,6 @@ packages:
|
||||
parse5@6.0.1:
|
||||
resolution: {integrity: sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==}
|
||||
|
||||
path-browserify@1.0.1:
|
||||
resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==}
|
||||
|
||||
pathe@2.0.3:
|
||||
resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
|
||||
|
||||
@@ -1833,9 +1680,6 @@ packages:
|
||||
yaml:
|
||||
optional: true
|
||||
|
||||
vscode-uri@3.1.0:
|
||||
resolution: {integrity: sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==}
|
||||
|
||||
vue-demi@0.14.10:
|
||||
resolution: {integrity: sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==}
|
||||
engines: {node: '>=12'}
|
||||
@@ -1863,12 +1707,6 @@ packages:
|
||||
peerDependencies:
|
||||
vue: ^3.2.0
|
||||
|
||||
vue-tsc@2.2.10:
|
||||
resolution: {integrity: sha512-jWZ1xSaNbabEV3whpIDMbjVSVawjAyW+x1n3JeGQo7S0uv2n9F/JMgWW90tGWNFRKya4YwKMZgCtr0vRAM7DeQ==}
|
||||
hasBin: true
|
||||
peerDependencies:
|
||||
typescript: '>=5.0.0'
|
||||
|
||||
vue-web-screen-shot@1.5.3:
|
||||
resolution: {integrity: sha512-aYyLr14ggSyCH+v5QivsRHtD6sYexhC0BFqmR0p+9qqfKQupSgzSxBAcQi6rqVEy69cEMb1yqFG34tDbjFwpIQ==}
|
||||
peerDependencies:
|
||||
@@ -2268,71 +2106,6 @@ snapshots:
|
||||
|
||||
'@sxzz/popperjs-es@2.11.7': {}
|
||||
|
||||
'@tauri-apps/api@2.5.0': {}
|
||||
|
||||
'@tauri-apps/cli-darwin-arm64@2.5.0':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-darwin-x64@2.5.0':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-arm-gnueabihf@2.5.0':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-arm64-gnu@2.5.0':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-arm64-musl@2.5.0':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-riscv64-gnu@2.5.0':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-x64-gnu@2.5.0':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-x64-musl@2.5.0':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-win32-arm64-msvc@2.5.0':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-win32-ia32-msvc@2.5.0':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-win32-x64-msvc@2.5.0':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli@2.5.0':
|
||||
optionalDependencies:
|
||||
'@tauri-apps/cli-darwin-arm64': 2.5.0
|
||||
'@tauri-apps/cli-darwin-x64': 2.5.0
|
||||
'@tauri-apps/cli-linux-arm-gnueabihf': 2.5.0
|
||||
'@tauri-apps/cli-linux-arm64-gnu': 2.5.0
|
||||
'@tauri-apps/cli-linux-arm64-musl': 2.5.0
|
||||
'@tauri-apps/cli-linux-riscv64-gnu': 2.5.0
|
||||
'@tauri-apps/cli-linux-x64-gnu': 2.5.0
|
||||
'@tauri-apps/cli-linux-x64-musl': 2.5.0
|
||||
'@tauri-apps/cli-win32-arm64-msvc': 2.5.0
|
||||
'@tauri-apps/cli-win32-ia32-msvc': 2.5.0
|
||||
'@tauri-apps/cli-win32-x64-msvc': 2.5.0
|
||||
|
||||
'@tauri-apps/plugin-fs@2.2.1':
|
||||
dependencies:
|
||||
'@tauri-apps/api': 2.5.0
|
||||
|
||||
'@tauri-apps/plugin-opener@2.2.6':
|
||||
dependencies:
|
||||
'@tauri-apps/api': 2.5.0
|
||||
|
||||
'@tauri-apps/plugin-os@2.2.1':
|
||||
dependencies:
|
||||
'@tauri-apps/api': 2.5.0
|
||||
|
||||
'@tauri-apps/plugin-sql@2.2.0':
|
||||
dependencies:
|
||||
'@tauri-apps/api': 2.5.0
|
||||
|
||||
'@tootallnate/once@2.0.0': {}
|
||||
|
||||
'@types/codemirror@0.0.108':
|
||||
@@ -2522,18 +2295,6 @@ snapshots:
|
||||
vite: 6.3.4(@types/node@22.15.3)(jiti@2.4.2)(sass@1.87.0)
|
||||
vue: 3.5.13(typescript@5.6.3)
|
||||
|
||||
'@volar/language-core@2.4.13':
|
||||
dependencies:
|
||||
'@volar/source-map': 2.4.13
|
||||
|
||||
'@volar/source-map@2.4.13': {}
|
||||
|
||||
'@volar/typescript@2.4.13':
|
||||
dependencies:
|
||||
'@volar/language-core': 2.4.13
|
||||
path-browserify: 1.0.1
|
||||
vscode-uri: 3.1.0
|
||||
|
||||
'@vue/compiler-core@3.5.13':
|
||||
dependencies:
|
||||
'@babel/parser': 7.27.1
|
||||
@@ -2564,26 +2325,8 @@ snapshots:
|
||||
'@vue/compiler-dom': 3.5.13
|
||||
'@vue/shared': 3.5.13
|
||||
|
||||
'@vue/compiler-vue2@2.7.16':
|
||||
dependencies:
|
||||
de-indent: 1.0.2
|
||||
he: 1.2.0
|
||||
|
||||
'@vue/devtools-api@6.6.4': {}
|
||||
|
||||
'@vue/language-core@2.2.10(typescript@5.6.3)':
|
||||
dependencies:
|
||||
'@volar/language-core': 2.4.13
|
||||
'@vue/compiler-dom': 3.5.13
|
||||
'@vue/compiler-vue2': 2.7.16
|
||||
'@vue/shared': 3.5.13
|
||||
alien-signals: 1.0.13
|
||||
minimatch: 9.0.5
|
||||
muggle-string: 0.4.1
|
||||
path-browserify: 1.0.1
|
||||
optionalDependencies:
|
||||
typescript: 5.6.3
|
||||
|
||||
'@vue/reactivity@3.5.13':
|
||||
dependencies:
|
||||
'@vue/shared': 3.5.13
|
||||
@@ -2646,8 +2389,6 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
alien-signals@1.0.13: {}
|
||||
|
||||
anymatch@3.1.3:
|
||||
dependencies:
|
||||
normalize-path: 3.0.0
|
||||
@@ -2665,16 +2406,10 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- debug
|
||||
|
||||
balanced-match@1.0.2: {}
|
||||
|
||||
base64-arraybuffer@1.0.2: {}
|
||||
|
||||
binary-extensions@2.3.0: {}
|
||||
|
||||
brace-expansion@2.0.1:
|
||||
dependencies:
|
||||
balanced-match: 1.0.2
|
||||
|
||||
braces@3.0.3:
|
||||
dependencies:
|
||||
fill-range: 7.1.1
|
||||
@@ -2997,8 +2732,6 @@ snapshots:
|
||||
|
||||
dayjs@1.11.13: {}
|
||||
|
||||
de-indent@1.0.2: {}
|
||||
|
||||
debug@4.4.0:
|
||||
dependencies:
|
||||
ms: 2.1.3
|
||||
@@ -3212,8 +2945,6 @@ snapshots:
|
||||
dependencies:
|
||||
function-bind: 1.1.2
|
||||
|
||||
he@1.2.0: {}
|
||||
|
||||
html-encoding-sniffer@3.0.0:
|
||||
dependencies:
|
||||
whatwg-encoding: 2.0.0
|
||||
@@ -3380,10 +3111,6 @@ snapshots:
|
||||
dependencies:
|
||||
mime-db: 1.52.0
|
||||
|
||||
minimatch@9.0.5:
|
||||
dependencies:
|
||||
brace-expansion: 2.0.1
|
||||
|
||||
mitt@3.0.1: {}
|
||||
|
||||
mlly@1.7.4:
|
||||
@@ -3399,8 +3126,6 @@ snapshots:
|
||||
|
||||
ms@2.1.3: {}
|
||||
|
||||
muggle-string@0.4.1: {}
|
||||
|
||||
nanoid@3.3.11: {}
|
||||
|
||||
node-addon-api@7.1.1:
|
||||
@@ -3439,8 +3164,6 @@ snapshots:
|
||||
|
||||
parse5@6.0.1: {}
|
||||
|
||||
path-browserify@1.0.1: {}
|
||||
|
||||
pathe@2.0.3: {}
|
||||
|
||||
perfect-debounce@1.0.0: {}
|
||||
@@ -3784,8 +3507,6 @@ snapshots:
|
||||
jiti: 2.4.2
|
||||
sass: 1.87.0
|
||||
|
||||
vscode-uri@3.1.0: {}
|
||||
|
||||
vue-demi@0.14.10(vue@3.5.13(typescript@5.6.3)):
|
||||
dependencies:
|
||||
vue: 3.5.13(typescript@5.6.3)
|
||||
@@ -3806,12 +3527,6 @@ snapshots:
|
||||
'@vue/devtools-api': 6.6.4
|
||||
vue: 3.5.13(typescript@5.6.3)
|
||||
|
||||
vue-tsc@2.2.10(typescript@5.6.3):
|
||||
dependencies:
|
||||
'@volar/typescript': 2.4.13
|
||||
'@vue/language-core': 2.2.10(typescript@5.6.3)
|
||||
typescript: 5.6.3
|
||||
|
||||
vue-web-screen-shot@1.5.3(core-js@3.42.0)(vue@3.5.13(typescript@5.6.3)):
|
||||
dependencies:
|
||||
core-js: 3.42.0
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ let localFile: any = null;
|
||||
|
||||
async function getLocalFile() {
|
||||
if (!localFile) {
|
||||
localFile = await import('@/api/local/service/files');
|
||||
//localFile = await import('@/api/local/service/files');
|
||||
}
|
||||
return localFile;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { createORM } from '../orm/orm.ts';
|
||||
// import { createORM } from '../orm/orm.ts';
|
||||
|
||||
interface Users {
|
||||
id?: number;
|
||||
username: string;
|
||||
password?: string;
|
||||
nickname?: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
isMaster: boolean;
|
||||
created_at?: Date;
|
||||
updated_at?: Date;
|
||||
}
|
||||
// interface Users {
|
||||
// id?: number;
|
||||
// username: string;
|
||||
// password?: string;
|
||||
// nickname?: string;
|
||||
// email?: string;
|
||||
// phone?: string;
|
||||
// isMaster: boolean;
|
||||
// created_at?: Date;
|
||||
// updated_at?: Date;
|
||||
// }
|
||||
|
||||
export const userDb = createORM<Users>('users');
|
||||
// export const userDb = createORM<Users>('users');
|
||||
+27
-27
@@ -1,28 +1,28 @@
|
||||
// src/api/local/db.ts
|
||||
import Database from '@tauri-apps/plugin-sql';
|
||||
import { migrationDatabase } from './migration';
|
||||
import { getPlatformInfo } from "@/utils/device";
|
||||
let dbInstance: Database | null = null;
|
||||
const { platform } = getPlatformInfo();
|
||||
export async function connectDatabase(dbPath: string = 'sqlite:godoos.db'): Promise<void> {
|
||||
if (!dbInstance) {
|
||||
dbInstance = await Database.load(dbPath);
|
||||
console.log('✅ 数据库已连接');
|
||||
}
|
||||
}
|
||||
export async function initDatabase() {
|
||||
if (platform === 'web')return null as any;
|
||||
await connectDatabase();
|
||||
await migrationDatabase();
|
||||
}
|
||||
export function getDatabase(){
|
||||
// // src/api/local/db.ts
|
||||
// import Database from '@tauri-apps/plugin-sql';
|
||||
// import { migrationDatabase } from './migration';
|
||||
// import { getPlatformInfo } from "@/utils/device";
|
||||
// let dbInstance: Database | null = null;
|
||||
// const { platform } = getPlatformInfo();
|
||||
// export async function connectDatabase(dbPath: string = 'sqlite:godoos.db'): Promise<void> {
|
||||
// if (!dbInstance) {
|
||||
// dbInstance = await Database.load(dbPath);
|
||||
// console.log('✅ 数据库已连接');
|
||||
// }
|
||||
// }
|
||||
// export async function initDatabase() {
|
||||
// if (platform === 'web')return null as any;
|
||||
// await connectDatabase();
|
||||
// await migrationDatabase();
|
||||
// }
|
||||
// export function getDatabase(){
|
||||
|
||||
if (platform === 'web')return null as any;
|
||||
if (!dbInstance) {
|
||||
// initDatabase().then(() => {
|
||||
// if (!dbInstance) throw new Error('数据库尚未连接,请先调用 connectDatabase');
|
||||
// });
|
||||
throw new Error('数据库尚未连接,请先调用 connectDatabase');
|
||||
}
|
||||
return dbInstance;
|
||||
}
|
||||
// if (platform === 'web')return null as any;
|
||||
// if (!dbInstance) {
|
||||
// // initDatabase().then(() => {
|
||||
// // if (!dbInstance) throw new Error('数据库尚未连接,请先调用 connectDatabase');
|
||||
// // });
|
||||
// throw new Error('数据库尚未连接,请先调用 connectDatabase');
|
||||
// }
|
||||
// return dbInstance;
|
||||
// }
|
||||
@@ -1,21 +1,21 @@
|
||||
import { getDatabase } from './db';
|
||||
// import { getDatabase } from './db';
|
||||
|
||||
export async function migrationDatabase(): Promise<void> {
|
||||
const db = getDatabase();
|
||||
//await db.execute('DROP TABLE IF EXISTS users');
|
||||
await db.execute(
|
||||
// `CREATE TABLE users (
|
||||
`CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
password TEXT NOT NULL,
|
||||
nickname TEXT,
|
||||
email TEXT,
|
||||
phone TEXT,
|
||||
isMaster INTEGER DEFAULT 0,
|
||||
created_at TEXT DEFAULT (DATETIME('now', 'localtime')),
|
||||
updated_at TEXT DEFAULT (DATETIME('now', 'localtime'))
|
||||
)`
|
||||
);
|
||||
console.log('✅ 用户表已初始化');
|
||||
}
|
||||
// export async function migrationDatabase(): Promise<void> {
|
||||
// const db = getDatabase();
|
||||
// //await db.execute('DROP TABLE IF EXISTS users');
|
||||
// await db.execute(
|
||||
// // `CREATE TABLE users (
|
||||
// `CREATE TABLE IF NOT EXISTS users (
|
||||
// id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
// username TEXT NOT NULL UNIQUE,
|
||||
// password TEXT NOT NULL,
|
||||
// nickname TEXT,
|
||||
// email TEXT,
|
||||
// phone TEXT,
|
||||
// isMaster INTEGER DEFAULT 0,
|
||||
// created_at TEXT DEFAULT (DATETIME('now', 'localtime')),
|
||||
// updated_at TEXT DEFAULT (DATETIME('now', 'localtime'))
|
||||
// )`
|
||||
// );
|
||||
// console.log('✅ 用户表已初始化');
|
||||
// }
|
||||
+193
-193
@@ -1,230 +1,230 @@
|
||||
// src/api/local/orm/orm.ts
|
||||
import { getDatabase } from './db';
|
||||
import Database from '@tauri-apps/plugin-sql';
|
||||
// const userORM = createORM<{ id: number; name: string; role: string }>('users');
|
||||
// // 查询并分页
|
||||
// await userORM.where({ role: 'admin' }).page(1, 10).select();
|
||||
// // 更新数据
|
||||
// await userORM.save({ role: 'admin' }).where({ id: 1 }).select();
|
||||
// // 统计数量
|
||||
// const total = await userORM.where({ role: 'admin' }).count();
|
||||
type Model = Record<string, any>;
|
||||
// // src/api/local/orm/orm.ts
|
||||
// import { getDatabase } from './db';
|
||||
// import Database from '@tauri-apps/plugin-sql';
|
||||
// // const userORM = createORM<{ id: number; name: string; role: string }>('users');
|
||||
// // // 查询并分页
|
||||
// // await userORM.where({ role: 'admin' }).page(1, 10).select();
|
||||
// // // 更新数据
|
||||
// // await userORM.save({ role: 'admin' }).where({ id: 1 }).select();
|
||||
// // // 统计数量
|
||||
// // const total = await userORM.where({ role: 'admin' }).count();
|
||||
// type Model = Record<string, any>;
|
||||
|
||||
interface ORM<T extends Model> {
|
||||
create: (data: T) => Promise<void>;
|
||||
update: (id: any, data: Partial<T>) => Promise<void>;
|
||||
save: (data: Partial<T>) => ORMQueryBuilder<T>;
|
||||
select: () => Promise<T[]>;
|
||||
find: () => Promise<T | null>;
|
||||
findById: (id: any) => Promise<T | null>;
|
||||
delete: (id: any) => Promise<void>;
|
||||
where: (conditions: Record<string, any>) => ORMQueryBuilder<T>;
|
||||
count: () => Promise<number>;
|
||||
page: (page: number, pageSize: number) => ORMQueryBuilder<T>;
|
||||
}
|
||||
// interface ORM<T extends Model> {
|
||||
// create: (data: T) => Promise<void>;
|
||||
// update: (id: any, data: Partial<T>) => Promise<void>;
|
||||
// save: (data: Partial<T>) => ORMQueryBuilder<T>;
|
||||
// select: () => Promise<T[]>;
|
||||
// find: () => Promise<T | null>;
|
||||
// findById: (id: any) => Promise<T | null>;
|
||||
// delete: (id: any) => Promise<void>;
|
||||
// where: (conditions: Record<string, any>) => ORMQueryBuilder<T>;
|
||||
// count: () => Promise<number>;
|
||||
// page: (page: number, pageSize: number) => ORMQueryBuilder<T>;
|
||||
// }
|
||||
|
||||
interface ORMQueryBuilder<T extends Model> {
|
||||
where: (conditions: Record<string, any>) => ORMQueryBuilder<T>;
|
||||
count: () => Promise<number>;
|
||||
page: (page: number, pageSize: number) => ORMQueryBuilder<T>;
|
||||
select: () => Promise<T[]>;
|
||||
find: () => Promise<T | null>;
|
||||
}
|
||||
// interface ORMQueryBuilder<T extends Model> {
|
||||
// where: (conditions: Record<string, any>) => ORMQueryBuilder<T>;
|
||||
// count: () => Promise<number>;
|
||||
// page: (page: number, pageSize: number) => ORMQueryBuilder<T>;
|
||||
// select: () => Promise<T[]>;
|
||||
// find: () => Promise<T | null>;
|
||||
// }
|
||||
|
||||
function createORMQueryBuilder<T extends Model>(
|
||||
db: Database,
|
||||
table: string
|
||||
): ORMQueryBuilder<T> {
|
||||
let conditions: Record<string, any> = {};
|
||||
let limit: number | null = null;
|
||||
let offset: number | null = null;
|
||||
// function createORMQueryBuilder<T extends Model>(
|
||||
// db: Database,
|
||||
// table: string
|
||||
// ): ORMQueryBuilder<T> {
|
||||
// let conditions: Record<string, any> = {};
|
||||
// let limit: number | null = null;
|
||||
// let offset: number | null = null;
|
||||
|
||||
function buildWhereClause(): { clause: string; values: any[] } {
|
||||
const clauses = [];
|
||||
const values = [];
|
||||
// function buildWhereClause(): { clause: string; values: any[] } {
|
||||
// const clauses = [];
|
||||
// const values = [];
|
||||
|
||||
for (const key in conditions) {
|
||||
if (conditions.hasOwnProperty(key)) {
|
||||
clauses.push(`${key} = $${values.length + 1}`);
|
||||
values.push(conditions[key]);
|
||||
}
|
||||
}
|
||||
// for (const key in conditions) {
|
||||
// if (conditions.hasOwnProperty(key)) {
|
||||
// clauses.push(`${key} = $${values.length + 1}`);
|
||||
// values.push(conditions[key]);
|
||||
// }
|
||||
// }
|
||||
|
||||
const whereClause = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
|
||||
return { clause: whereClause, values };
|
||||
}
|
||||
// const whereClause = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
|
||||
// return { clause: whereClause, values };
|
||||
// }
|
||||
|
||||
const queryBuilder: ORMQueryBuilder<T> = {
|
||||
where: (newConditions: Record<string, any>): ORMQueryBuilder<T> => {
|
||||
conditions = { ...conditions, ...newConditions };
|
||||
return queryBuilder;
|
||||
},
|
||||
count: async (): Promise<number> => {
|
||||
const { clause, values } = buildWhereClause();
|
||||
const query = `SELECT COUNT(*) as count FROM ${table} ${clause}`;
|
||||
const result: any = await db.select(query, values);
|
||||
return result[0]?.count || 0;
|
||||
},
|
||||
page: (page: number, pageSize: number): ORMQueryBuilder<T> => {
|
||||
const newLimit = pageSize;
|
||||
const newOffset = (page - 1) * pageSize;
|
||||
limit = newLimit;
|
||||
offset = newOffset;
|
||||
return queryBuilder;
|
||||
},
|
||||
select: async (): Promise<T[]> => {
|
||||
const { clause, values } = buildWhereClause();
|
||||
// const queryBuilder: ORMQueryBuilder<T> = {
|
||||
// where: (newConditions: Record<string, any>): ORMQueryBuilder<T> => {
|
||||
// conditions = { ...conditions, ...newConditions };
|
||||
// return queryBuilder;
|
||||
// },
|
||||
// count: async (): Promise<number> => {
|
||||
// const { clause, values } = buildWhereClause();
|
||||
// const query = `SELECT COUNT(*) as count FROM ${table} ${clause}`;
|
||||
// const result: any = await db.select(query, values);
|
||||
// return result[0]?.count || 0;
|
||||
// },
|
||||
// page: (page: number, pageSize: number): ORMQueryBuilder<T> => {
|
||||
// const newLimit = pageSize;
|
||||
// const newOffset = (page - 1) * pageSize;
|
||||
// limit = newLimit;
|
||||
// offset = newOffset;
|
||||
// return queryBuilder;
|
||||
// },
|
||||
// select: async (): Promise<T[]> => {
|
||||
// const { clause, values } = buildWhereClause();
|
||||
|
||||
let limitClause = '';
|
||||
if (limit !== null && offset !== null) {
|
||||
limitClause = `LIMIT ${limit} OFFSET ${offset}`;
|
||||
}
|
||||
// let limitClause = '';
|
||||
// if (limit !== null && offset !== null) {
|
||||
// limitClause = `LIMIT ${limit} OFFSET ${offset}`;
|
||||
// }
|
||||
|
||||
const query = `SELECT * FROM ${table} ${clause} ${limitClause}`;
|
||||
const result = await db.select(query, values);
|
||||
return result as T[];
|
||||
},
|
||||
find: async (): Promise<T | null> => {
|
||||
const { clause, values } = buildWhereClause();
|
||||
// const query = `SELECT * FROM ${table} ${clause} ${limitClause}`;
|
||||
// const result = await db.select(query, values);
|
||||
// return result as T[];
|
||||
// },
|
||||
// find: async (): Promise<T | null> => {
|
||||
// const { clause, values } = buildWhereClause();
|
||||
|
||||
// 加 LIMIT 1 只取一条记录
|
||||
const query = `SELECT * FROM ${table} ${clause} LIMIT 1`;
|
||||
const result:any = await db.select(query, values);
|
||||
// // 加 LIMIT 1 只取一条记录
|
||||
// const query = `SELECT * FROM ${table} ${clause} LIMIT 1`;
|
||||
// const result:any = await db.select(query, values);
|
||||
|
||||
return result.length > 0 ? (result[0] as T) : null;
|
||||
}
|
||||
};
|
||||
// return result.length > 0 ? (result[0] as T) : null;
|
||||
// }
|
||||
// };
|
||||
|
||||
return queryBuilder;
|
||||
}
|
||||
// return queryBuilder;
|
||||
// }
|
||||
|
||||
function buildWhereClauseFromConditions(
|
||||
conditions: Record<string, any>
|
||||
): { clause: string; values: any[] } {
|
||||
const clauses = [];
|
||||
const values = [];
|
||||
// function buildWhereClauseFromConditions(
|
||||
// conditions: Record<string, any>
|
||||
// ): { clause: string; values: any[] } {
|
||||
// const clauses = [];
|
||||
// const values = [];
|
||||
|
||||
for (const key in conditions) {
|
||||
if (conditions.hasOwnProperty(key)) {
|
||||
clauses.push(`${key} = $${values.length + 1}`);
|
||||
values.push(conditions[key]);
|
||||
}
|
||||
}
|
||||
// for (const key in conditions) {
|
||||
// if (conditions.hasOwnProperty(key)) {
|
||||
// clauses.push(`${key} = $${values.length + 1}`);
|
||||
// values.push(conditions[key]);
|
||||
// }
|
||||
// }
|
||||
|
||||
const whereClause = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
|
||||
return { clause: whereClause, values };
|
||||
}
|
||||
// const whereClause = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
|
||||
// return { clause: whereClause, values };
|
||||
// }
|
||||
|
||||
async function executeUpdate<T extends Model>(
|
||||
db: Database,
|
||||
table: string,
|
||||
data: Partial<T>,
|
||||
conditions: Record<string, any>
|
||||
): Promise<void> {
|
||||
const now = new Date().toISOString();
|
||||
const timestampedData = { ...data, updated_at: now };
|
||||
const setClause = Object.keys(timestampedData)
|
||||
.map((key, i) => `${key} = $${i + 1}`)
|
||||
.join(', ');
|
||||
const values = Object.values(timestampedData);
|
||||
// async function executeUpdate<T extends Model>(
|
||||
// db: Database,
|
||||
// table: string,
|
||||
// data: Partial<T>,
|
||||
// conditions: Record<string, any>
|
||||
// ): Promise<void> {
|
||||
// const now = new Date().toISOString();
|
||||
// const timestampedData = { ...data, updated_at: now };
|
||||
// const setClause = Object.keys(timestampedData)
|
||||
// .map((key, i) => `${key} = $${i + 1}`)
|
||||
// .join(', ');
|
||||
// const values = Object.values(timestampedData);
|
||||
|
||||
const { clause: whereClause, values: whereValues } = buildWhereClauseFromConditions(conditions);
|
||||
// const { clause: whereClause, values: whereValues } = buildWhereClauseFromConditions(conditions);
|
||||
|
||||
const query = `UPDATE ${table} SET ${setClause} ${whereClause}`;
|
||||
await db.execute(query, [...values, ...whereValues]);
|
||||
}
|
||||
// const query = `UPDATE ${table} SET ${setClause} ${whereClause}`;
|
||||
// await db.execute(query, [...values, ...whereValues]);
|
||||
// }
|
||||
|
||||
export function createORM<T extends Model>(table: string): ORM<T> {
|
||||
const db = getDatabase();
|
||||
if (!db) {
|
||||
throw new Error('Database not initialized');
|
||||
}
|
||||
// export function createORM<T extends Model>(table: string): ORM<T> {
|
||||
// const db = getDatabase();
|
||||
// if (!db) {
|
||||
// throw new Error('Database not initialized');
|
||||
// }
|
||||
|
||||
const ormInstance: ORM<T> = {
|
||||
create: async (data: T): Promise<void> => {
|
||||
const now = new Date().toISOString();
|
||||
const timestampedData = {
|
||||
...data,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
};
|
||||
// const ormInstance: ORM<T> = {
|
||||
// create: async (data: T): Promise<void> => {
|
||||
// const now = new Date().toISOString();
|
||||
// const timestampedData = {
|
||||
// ...data,
|
||||
// created_at: now,
|
||||
// updated_at: now,
|
||||
// };
|
||||
|
||||
const columns = Object.keys(timestampedData).join(', ');
|
||||
const placeholders = Object.keys(timestampedData)
|
||||
.map((_, i) => `$${i + 1}`)
|
||||
.join(', ');
|
||||
const values = Object.values(timestampedData);
|
||||
// const columns = Object.keys(timestampedData).join(', ');
|
||||
// const placeholders = Object.keys(timestampedData)
|
||||
// .map((_, i) => `$${i + 1}`)
|
||||
// .join(', ');
|
||||
// const values = Object.values(timestampedData);
|
||||
|
||||
const query = `INSERT INTO ${table} (${columns}) VALUES (${placeholders})`;
|
||||
await db.execute(query, values);
|
||||
},
|
||||
// const query = `INSERT INTO ${table} (${columns}) VALUES (${placeholders})`;
|
||||
// await db.execute(query, values);
|
||||
// },
|
||||
|
||||
update: async (id: any, data: Partial<T>): Promise<void> => {
|
||||
const now = new Date().toISOString();
|
||||
const timestampedData = {
|
||||
...data,
|
||||
updated_at: now,
|
||||
};
|
||||
// update: async (id: any, data: Partial<T>): Promise<void> => {
|
||||
// const now = new Date().toISOString();
|
||||
// const timestampedData = {
|
||||
// ...data,
|
||||
// updated_at: now,
|
||||
// };
|
||||
|
||||
const setClause = Object.keys(timestampedData)
|
||||
.map((key, i) => `${key} = $${i + 1}`)
|
||||
.join(', ');
|
||||
// const setClause = Object.keys(timestampedData)
|
||||
// .map((key, i) => `${key} = $${i + 1}`)
|
||||
// .join(', ');
|
||||
|
||||
const values = Object.values(timestampedData);
|
||||
const query = `UPDATE ${table} SET ${setClause} WHERE id = $${values.length + 1}`;
|
||||
values.push(id);
|
||||
// const values = Object.values(timestampedData);
|
||||
// const query = `UPDATE ${table} SET ${setClause} WHERE id = $${values.length + 1}`;
|
||||
// values.push(id);
|
||||
|
||||
await db.execute(query, values);
|
||||
},
|
||||
// await db.execute(query, values);
|
||||
// },
|
||||
|
||||
save: (data: Partial<T>): ORMQueryBuilder<T> => {
|
||||
const queryBuilder = createORMQueryBuilder<T>(db, table);
|
||||
// save: (data: Partial<T>): ORMQueryBuilder<T> => {
|
||||
// const queryBuilder = createORMQueryBuilder<T>(db, table);
|
||||
|
||||
const originalWhere = queryBuilder.where;
|
||||
queryBuilder.where = (conditions: Record<string, any>): ORMQueryBuilder<T> => {
|
||||
const updatedQueryBuilder = originalWhere(conditions);
|
||||
// const originalWhere = queryBuilder.where;
|
||||
// queryBuilder.where = (conditions: Record<string, any>): ORMQueryBuilder<T> => {
|
||||
// const updatedQueryBuilder = originalWhere(conditions);
|
||||
|
||||
updatedQueryBuilder.select = async (): Promise<T[]> => {
|
||||
await executeUpdate(db, table, data, conditions);
|
||||
return [];
|
||||
};
|
||||
// updatedQueryBuilder.select = async (): Promise<T[]> => {
|
||||
// await executeUpdate(db, table, data, conditions);
|
||||
// return [];
|
||||
// };
|
||||
|
||||
return updatedQueryBuilder;
|
||||
};
|
||||
// return updatedQueryBuilder;
|
||||
// };
|
||||
|
||||
return queryBuilder;
|
||||
},
|
||||
// return queryBuilder;
|
||||
// },
|
||||
|
||||
select: (): Promise<T[]> => {
|
||||
return createORMQueryBuilder<T>(db, table).select();
|
||||
},
|
||||
find: async (): Promise<T | null> => {
|
||||
return createORMQueryBuilder<T>(db, table).find();
|
||||
},
|
||||
findById: async (id: any): Promise<T | null> => {
|
||||
const query = `SELECT * FROM ${table} WHERE id = $1`;
|
||||
const result: any = await db.select(query, [id]);
|
||||
return result.length > 0 ? (result[0] as T) : null;
|
||||
},
|
||||
// select: (): Promise<T[]> => {
|
||||
// return createORMQueryBuilder<T>(db, table).select();
|
||||
// },
|
||||
// find: async (): Promise<T | null> => {
|
||||
// return createORMQueryBuilder<T>(db, table).find();
|
||||
// },
|
||||
// findById: async (id: any): Promise<T | null> => {
|
||||
// const query = `SELECT * FROM ${table} WHERE id = $1`;
|
||||
// const result: any = await db.select(query, [id]);
|
||||
// return result.length > 0 ? (result[0] as T) : null;
|
||||
// },
|
||||
|
||||
delete: async (id: any): Promise<void> => {
|
||||
const query = `DELETE FROM ${table} WHERE id = $1`;
|
||||
await db.execute(query, [id]);
|
||||
},
|
||||
// delete: async (id: any): Promise<void> => {
|
||||
// const query = `DELETE FROM ${table} WHERE id = $1`;
|
||||
// await db.execute(query, [id]);
|
||||
// },
|
||||
|
||||
where: (conditions: Record<string, any>): ORMQueryBuilder<T> => {
|
||||
console.log('where', conditions);
|
||||
return createORMQueryBuilder<T>(db, table).where(conditions);
|
||||
},
|
||||
// where: (conditions: Record<string, any>): ORMQueryBuilder<T> => {
|
||||
// console.log('where', conditions);
|
||||
// return createORMQueryBuilder<T>(db, table).where(conditions);
|
||||
// },
|
||||
|
||||
count: (): Promise<number> => {
|
||||
return createORMQueryBuilder<T>(db, table).count();
|
||||
},
|
||||
// count: (): Promise<number> => {
|
||||
// return createORMQueryBuilder<T>(db, table).count();
|
||||
// },
|
||||
|
||||
page: (page: number, pageSize: number): ORMQueryBuilder<T> => {
|
||||
return createORMQueryBuilder<T>(db, table).page(page, pageSize);
|
||||
},
|
||||
};
|
||||
// page: (page: number, pageSize: number): ORMQueryBuilder<T> => {
|
||||
// return createORMQueryBuilder<T>(db, table).page(page, pageSize);
|
||||
// },
|
||||
// };
|
||||
|
||||
return ormInstance;
|
||||
}
|
||||
// return ormInstance;
|
||||
// }
|
||||
@@ -1,40 +1,40 @@
|
||||
import { userDb } from "../models/users"
|
||||
import { success, error } from "./msg"
|
||||
import { md5 } from "js-md5"
|
||||
import { toRaw } from "vue"
|
||||
// import * as cache from "../cache"
|
||||
import { sign,generate16BitString } from './jwt'
|
||||
import { setToken, setUsername } from '@/utils/request'
|
||||
import { initOsSystem } from "./os"
|
||||
export async function loginIn(params: any) {
|
||||
//console.log(toRaw(params.param))
|
||||
const param = toRaw(params.param)
|
||||
const user = await userDb.where({ username : param.username }).find()
|
||||
if (!user) return error("用户不存在,请注册用户!")
|
||||
if(md5(param.password) !== user.password) return error("密码错误")
|
||||
const salt = generate16BitString()
|
||||
const token = sign({id:user.id}, salt, { expiresIn: '24h' })
|
||||
//console.log(token)
|
||||
setToken(token)
|
||||
setUsername(user.username)
|
||||
//cache.set("userid:"+user.id, salt)
|
||||
await initOsSystem()
|
||||
return success("登录成功", {user})
|
||||
}
|
||||
export async function logout() {
|
||||
// import { userDb } from "../models/users"
|
||||
// import { success, error } from "./msg"
|
||||
// import { md5 } from "js-md5"
|
||||
// import { toRaw } from "vue"
|
||||
// // import * as cache from "../cache"
|
||||
// import { sign,generate16BitString } from './jwt'
|
||||
// import { setToken, setUsername } from '@/utils/request'
|
||||
// import { initOsSystem } from "./os"
|
||||
// export async function loginIn(params: any) {
|
||||
// //console.log(toRaw(params.param))
|
||||
// const param = toRaw(params.param)
|
||||
// const user = await userDb.where({ username : param.username }).find()
|
||||
// if (!user) return error("用户不存在,请注册用户!")
|
||||
// if(md5(param.password) !== user.password) return error("密码错误")
|
||||
// const salt = generate16BitString()
|
||||
// const token = sign({id:user.id}, salt, { expiresIn: '24h' })
|
||||
// //console.log(token)
|
||||
// setToken(token)
|
||||
// setUsername(user.username)
|
||||
// //cache.set("userid:"+user.id, salt)
|
||||
// await initOsSystem()
|
||||
// return success("登录成功", {user})
|
||||
// }
|
||||
// export async function logout() {
|
||||
|
||||
}
|
||||
export async function register(params: any) {
|
||||
//console.log(params)
|
||||
const user = await userDb.where({ username : params.username }).find()
|
||||
if (user) return error("用户已存在")
|
||||
params.password = md5(params.password)
|
||||
await userDb.create(params)
|
||||
return success("注册成功", params)
|
||||
}
|
||||
export async function isLogin():Promise<boolean> {
|
||||
return false
|
||||
}
|
||||
export async function getThirdpartyList() {
|
||||
return []
|
||||
}
|
||||
// }
|
||||
// export async function register(params: any) {
|
||||
// //console.log(params)
|
||||
// const user = await userDb.where({ username : params.username }).find()
|
||||
// if (user) return error("用户已存在")
|
||||
// params.password = md5(params.password)
|
||||
// await userDb.create(params)
|
||||
// return success("注册成功", params)
|
||||
// }
|
||||
// export async function isLogin():Promise<boolean> {
|
||||
// return false
|
||||
// }
|
||||
// export async function getThirdpartyList() {
|
||||
// return []
|
||||
// }
|
||||
+288
-288
@@ -1,297 +1,297 @@
|
||||
import * as fs from '@tauri-apps/plugin-fs';
|
||||
import * as ps from '@tauri-apps/api/path';
|
||||
import { base64ToBuffer, isBase64 } from '@/utils/file'
|
||||
import { getUsername } from '@/utils/request';
|
||||
const basedir = fs.BaseDirectory.Home
|
||||
export async function appPath() {
|
||||
const resourcePath = await ps.homeDir();
|
||||
//const resourcePath = await ps.appDataDir();
|
||||
const username:string = getUsername();
|
||||
const appDir = await ps.join(resourcePath, ".godoos", username);
|
||||
if (!await fs.exists(appDir, { baseDir: basedir })) {
|
||||
await fs.mkdir(appDir, { baseDir: basedir, recursive: true });
|
||||
}
|
||||
return appDir;
|
||||
}
|
||||
export async function resolvePath(path: string) {
|
||||
const appDir = await appPath();
|
||||
return await ps.join(appDir, path);
|
||||
}
|
||||
export async function parseDir(path:string,entries: any) {
|
||||
const appDir = await appPath();
|
||||
path = path.replace(appDir, '');
|
||||
// import * as fs from '@tauri-apps/plugin-fs';
|
||||
// import * as ps from '@tauri-apps/api/path';
|
||||
// import { base64ToBuffer, isBase64 } from '@/utils/file'
|
||||
// import { getUsername } from '@/utils/request';
|
||||
// const basedir = fs.BaseDirectory.Home
|
||||
// export async function appPath() {
|
||||
// const resourcePath = await ps.homeDir();
|
||||
// //const resourcePath = await ps.appDataDir();
|
||||
// const username:string = getUsername();
|
||||
// const appDir = await ps.join(resourcePath, ".godoos", username);
|
||||
// if (!await fs.exists(appDir, { baseDir: basedir })) {
|
||||
// await fs.mkdir(appDir, { baseDir: basedir, recursive: true });
|
||||
// }
|
||||
// return appDir;
|
||||
// }
|
||||
// export async function resolvePath(path: string) {
|
||||
// const appDir = await appPath();
|
||||
// return await ps.join(appDir, path);
|
||||
// }
|
||||
// export async function parseDir(path:string,entries: any) {
|
||||
// const appDir = await appPath();
|
||||
// path = path.replace(appDir, '');
|
||||
|
||||
entries.forEach(async(entry:any) => {
|
||||
entry.path = join(path, entry.name);
|
||||
entry.isPwd = false;
|
||||
if(entry.isFile){
|
||||
const ns = entry.name.split('.')
|
||||
entry.ext = ns[1];
|
||||
entry.title = ns[0];
|
||||
if(entry.ext == 'exe' || entry.ext == 'lnk'){
|
||||
const entryPath = join(appDir, entry.path)
|
||||
entry.content = await fs.readTextFile(entryPath, { baseDir: basedir })
|
||||
}
|
||||
}else{
|
||||
entry.title = entry.name;
|
||||
}
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
data: entries
|
||||
};
|
||||
}
|
||||
export async function read(path: string, pwd?: string) {
|
||||
path = await resolvePath(path);
|
||||
const entries = await fs.readDir(path, { baseDir: basedir });
|
||||
//processEntriesRecursive(path, entries);
|
||||
return parseDir(path,entries);
|
||||
}
|
||||
export async function readFile(path: string, pwd?: string) {
|
||||
path = await resolvePath(path);
|
||||
const data = await fs.readTextFile(path, { baseDir: basedir });
|
||||
return {
|
||||
success: true,
|
||||
data: data
|
||||
}
|
||||
}
|
||||
export async function stat(path: string) {
|
||||
path = await resolvePath(path);
|
||||
const response = await fs.stat(path, { baseDir: basedir })
|
||||
return response;
|
||||
}
|
||||
export async function desktop() {
|
||||
const apps = await read("C/Users/Desktop");
|
||||
//console.log(apps)
|
||||
const menulist = await read("C/Users/Menulist");
|
||||
return { apps : apps.data, menulist: menulist.data };
|
||||
}
|
||||
export async function exists(path: string) {
|
||||
path = await resolvePath(path);
|
||||
return await fs.exists(path, { baseDir: basedir });
|
||||
// entries.forEach(async(entry:any) => {
|
||||
// entry.path = join(path, entry.name);
|
||||
// entry.isPwd = false;
|
||||
// if(entry.isFile){
|
||||
// const ns = entry.name.split('.')
|
||||
// entry.ext = ns[1];
|
||||
// entry.title = ns[0];
|
||||
// if(entry.ext == 'exe' || entry.ext == 'lnk'){
|
||||
// const entryPath = join(appDir, entry.path)
|
||||
// entry.content = await fs.readTextFile(entryPath, { baseDir: basedir })
|
||||
// }
|
||||
// }else{
|
||||
// entry.title = entry.name;
|
||||
// }
|
||||
// });
|
||||
// return {
|
||||
// success: true,
|
||||
// data: entries
|
||||
// };
|
||||
// }
|
||||
// export async function read(path: string, pwd?: string) {
|
||||
// path = await resolvePath(path);
|
||||
// const entries = await fs.readDir(path, { baseDir: basedir });
|
||||
// //processEntriesRecursive(path, entries);
|
||||
// return parseDir(path,entries);
|
||||
// }
|
||||
// export async function readFile(path: string, pwd?: string) {
|
||||
// path = await resolvePath(path);
|
||||
// const data = await fs.readTextFile(path, { baseDir: basedir });
|
||||
// return {
|
||||
// success: true,
|
||||
// data: data
|
||||
// }
|
||||
// }
|
||||
// export async function stat(path: string) {
|
||||
// path = await resolvePath(path);
|
||||
// const response = await fs.stat(path, { baseDir: basedir })
|
||||
// return response;
|
||||
// }
|
||||
// export async function desktop() {
|
||||
// const apps = await read("C/Users/Desktop");
|
||||
// //console.log(apps)
|
||||
// const menulist = await read("C/Users/Menulist");
|
||||
// return { apps : apps.data, menulist: menulist.data };
|
||||
// }
|
||||
// export async function exists(path: string) {
|
||||
// path = await resolvePath(path);
|
||||
// return await fs.exists(path, { baseDir: basedir });
|
||||
|
||||
}
|
||||
export async function mkdir(path: string) {
|
||||
if (path.length < 2 || path.charAt(1) == 'B') {
|
||||
return false;
|
||||
}
|
||||
path = await resolvePath(path);
|
||||
return await fs.mkdir(path, { baseDir: basedir });
|
||||
}
|
||||
export async function rmdir(dirPath: string) {
|
||||
if (dirPath.length < 3) {
|
||||
return false;
|
||||
}
|
||||
const ext = dirPath.split('.').pop();
|
||||
if (ext == 'exe') {
|
||||
return false;
|
||||
}
|
||||
dirPath = await resolvePath(dirPath);
|
||||
return await fs.remove(dirPath, { baseDir: basedir });
|
||||
}
|
||||
export function restore(dirPath: string) {
|
||||
if (dirPath.length < 2) {
|
||||
return false;
|
||||
}
|
||||
// }
|
||||
// export async function mkdir(path: string) {
|
||||
// if (path.length < 2 || path.charAt(1) == 'B') {
|
||||
// return false;
|
||||
// }
|
||||
// path = await resolvePath(path);
|
||||
// return await fs.mkdir(path, { baseDir: basedir });
|
||||
// }
|
||||
// export async function rmdir(dirPath: string) {
|
||||
// if (dirPath.length < 3) {
|
||||
// return false;
|
||||
// }
|
||||
// const ext = dirPath.split('.').pop();
|
||||
// if (ext == 'exe') {
|
||||
// return false;
|
||||
// }
|
||||
// dirPath = await resolvePath(dirPath);
|
||||
// return await fs.remove(dirPath, { baseDir: basedir });
|
||||
// }
|
||||
// export function restore(dirPath: string) {
|
||||
// if (dirPath.length < 2) {
|
||||
// return false;
|
||||
// }
|
||||
|
||||
return false;
|
||||
}
|
||||
export function favorite(path: string) {
|
||||
if (path.length < 2) {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
export function pwd(path: string, pwd: string) {
|
||||
if (path.length < 2) {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
export function unpwd(path: string, pwd: string) {
|
||||
if (path.length < 2) {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
export async function rename(oldPath: string, newPath: string) {
|
||||
if (oldPath.length < 2) {
|
||||
return false;
|
||||
}
|
||||
oldPath = await resolvePath(oldPath);
|
||||
newPath = await resolvePath(newPath);
|
||||
return await fs.rename(oldPath, newPath, { oldPathBaseDir: basedir, newPathBaseDir: basedir });
|
||||
// return false;
|
||||
// }
|
||||
// export function favorite(path: string) {
|
||||
// if (path.length < 2) {
|
||||
// return false;
|
||||
// }
|
||||
// return false;
|
||||
// }
|
||||
// export function pwd(path: string, pwd: string) {
|
||||
// if (path.length < 2) {
|
||||
// return false;
|
||||
// }
|
||||
// return false;
|
||||
// }
|
||||
// export function unpwd(path: string, pwd: string) {
|
||||
// if (path.length < 2) {
|
||||
// return false;
|
||||
// }
|
||||
// return false;
|
||||
// }
|
||||
// export async function rename(oldPath: string, newPath: string) {
|
||||
// if (oldPath.length < 2) {
|
||||
// return false;
|
||||
// }
|
||||
// oldPath = await resolvePath(oldPath);
|
||||
// newPath = await resolvePath(newPath);
|
||||
// return await fs.rename(oldPath, newPath, { oldPathBaseDir: basedir, newPathBaseDir: basedir });
|
||||
|
||||
}
|
||||
export async function clear() {
|
||||
const appDir = await appPath();
|
||||
return await fs.remove(appDir, { baseDir: basedir });
|
||||
}
|
||||
export function search(path: string, query: string) {
|
||||
return false
|
||||
}
|
||||
export async function copy(srcPath: string, dstPath: string) {
|
||||
srcPath = await resolvePath(srcPath);
|
||||
dstPath = await resolvePath(dstPath);
|
||||
return await fs.copyFile(srcPath, dstPath, { fromPathBaseDir: basedir, toPathBaseDir: basedir });
|
||||
}
|
||||
// }
|
||||
// export async function clear() {
|
||||
// const appDir = await appPath();
|
||||
// return await fs.remove(appDir, { baseDir: basedir });
|
||||
// }
|
||||
// export function search(path: string, query: string) {
|
||||
// return false
|
||||
// }
|
||||
// export async function copy(srcPath: string, dstPath: string) {
|
||||
// srcPath = await resolvePath(srcPath);
|
||||
// dstPath = await resolvePath(dstPath);
|
||||
// return await fs.copyFile(srcPath, dstPath, { fromPathBaseDir: basedir, toPathBaseDir: basedir });
|
||||
// }
|
||||
|
||||
|
||||
export async function unlink(path: string) {
|
||||
if (path.length < 2) {
|
||||
return false;
|
||||
}
|
||||
const ext = path.split('.').pop();
|
||||
if (ext == 'exe') {
|
||||
return false;
|
||||
}
|
||||
path = await resolvePath(path);
|
||||
return await fs.remove(path, { baseDir: basedir });
|
||||
}
|
||||
export function parserFormData(content: any, contentType: any) {
|
||||
if (!content || content == '') {
|
||||
return new Blob([], { type: 'text/plain;charset=utf-8' });
|
||||
}
|
||||
if (contentType == 'text') {
|
||||
return new Blob([content], { type: 'text/plain;charset=utf-8' });
|
||||
}
|
||||
else if (contentType == 'base64') {
|
||||
if (content.indexOf(";base64,") > -1) {
|
||||
const parts = content.split(";base64,");
|
||||
content = parts[1];
|
||||
}
|
||||
content = base64ToBuffer(content);
|
||||
return new Blob([content]);
|
||||
}
|
||||
else if (typeof content === 'object' && content !== null && 'data' in content && Array.isArray(content.data)) {
|
||||
return new Blob([new Uint8Array(content.data).buffer]);
|
||||
}
|
||||
else if (contentType == 'buffer') {
|
||||
return new Blob([content]);
|
||||
}
|
||||
}
|
||||
export function getFormData(content: any) {
|
||||
let blobContent: Blob;
|
||||
//console.log(content)
|
||||
if (typeof content === 'string') {
|
||||
if (content) { // 检查 content 是否为空
|
||||
if (isBase64(content)) {
|
||||
if (content.indexOf(";base64,") > -1) {
|
||||
const parts = content.split(";base64,");
|
||||
content = parts[1];
|
||||
}
|
||||
content = base64ToBuffer(content);
|
||||
blobContent = new Blob([content]);
|
||||
} else {
|
||||
//console.log(content)
|
||||
blobContent = new Blob([content], { type: 'text/plain;charset=utf-8' });
|
||||
}
|
||||
} else {
|
||||
// 处理 content 为空的情况
|
||||
blobContent = new Blob([], { type: 'text/plain;charset=utf-8' });
|
||||
}
|
||||
}
|
||||
else if (content instanceof Blob) {
|
||||
// 如果是Blob,直接使用
|
||||
blobContent = content;
|
||||
}
|
||||
else if ('data' in content && Array.isArray(content.data)) {
|
||||
// 假设data属性是一个字节数组,将其转换为ArrayBuffer
|
||||
const arrayBuffer = new Uint8Array(content.data).buffer;
|
||||
//console.log(arrayBuffer)
|
||||
blobContent = new Blob([arrayBuffer]);
|
||||
} else if (content instanceof ArrayBuffer) {
|
||||
// 如果已经是ArrayBuffer,直接使用
|
||||
blobContent = new Blob([content]);
|
||||
}
|
||||
else if (content instanceof Array || content instanceof Object) {
|
||||
// 如果是数组
|
||||
blobContent = new Blob([JSON.stringify(content)], { type: 'text/plain;charset=utf-8' });
|
||||
} else {
|
||||
throw new Error('Unsupported content format');
|
||||
}
|
||||
// export async function unlink(path: string) {
|
||||
// if (path.length < 2) {
|
||||
// return false;
|
||||
// }
|
||||
// const ext = path.split('.').pop();
|
||||
// if (ext == 'exe') {
|
||||
// return false;
|
||||
// }
|
||||
// path = await resolvePath(path);
|
||||
// return await fs.remove(path, { baseDir: basedir });
|
||||
// }
|
||||
// export function parserFormData(content: any, contentType: any) {
|
||||
// if (!content || content == '') {
|
||||
// return new Blob([], { type: 'text/plain;charset=utf-8' });
|
||||
// }
|
||||
// if (contentType == 'text') {
|
||||
// return new Blob([content], { type: 'text/plain;charset=utf-8' });
|
||||
// }
|
||||
// else if (contentType == 'base64') {
|
||||
// if (content.indexOf(";base64,") > -1) {
|
||||
// const parts = content.split(";base64,");
|
||||
// content = parts[1];
|
||||
// }
|
||||
// content = base64ToBuffer(content);
|
||||
// return new Blob([content]);
|
||||
// }
|
||||
// else if (typeof content === 'object' && content !== null && 'data' in content && Array.isArray(content.data)) {
|
||||
// return new Blob([new Uint8Array(content.data).buffer]);
|
||||
// }
|
||||
// else if (contentType == 'buffer') {
|
||||
// return new Blob([content]);
|
||||
// }
|
||||
// }
|
||||
// export function getFormData(content: any) {
|
||||
// let blobContent: Blob;
|
||||
// //console.log(content)
|
||||
// if (typeof content === 'string') {
|
||||
// if (content) { // 检查 content 是否为空
|
||||
// if (isBase64(content)) {
|
||||
// if (content.indexOf(";base64,") > -1) {
|
||||
// const parts = content.split(";base64,");
|
||||
// content = parts[1];
|
||||
// }
|
||||
// content = base64ToBuffer(content);
|
||||
// blobContent = new Blob([content]);
|
||||
// } else {
|
||||
// //console.log(content)
|
||||
// blobContent = new Blob([content], { type: 'text/plain;charset=utf-8' });
|
||||
// }
|
||||
// } else {
|
||||
// // 处理 content 为空的情况
|
||||
// blobContent = new Blob([], { type: 'text/plain;charset=utf-8' });
|
||||
// }
|
||||
// }
|
||||
// else if (content instanceof Blob) {
|
||||
// // 如果是Blob,直接使用
|
||||
// blobContent = content;
|
||||
// }
|
||||
// else if ('data' in content && Array.isArray(content.data)) {
|
||||
// // 假设data属性是一个字节数组,将其转换为ArrayBuffer
|
||||
// const arrayBuffer = new Uint8Array(content.data).buffer;
|
||||
// //console.log(arrayBuffer)
|
||||
// blobContent = new Blob([arrayBuffer]);
|
||||
// } else if (content instanceof ArrayBuffer) {
|
||||
// // 如果已经是ArrayBuffer,直接使用
|
||||
// blobContent = new Blob([content]);
|
||||
// }
|
||||
// else if (content instanceof Array || content instanceof Object) {
|
||||
// // 如果是数组
|
||||
// blobContent = new Blob([JSON.stringify(content)], { type: 'text/plain;charset=utf-8' });
|
||||
// } else {
|
||||
// throw new Error('Unsupported content format');
|
||||
// }
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('content', blobContent);
|
||||
return formData
|
||||
}
|
||||
export async function writeFile(path: string, data: any, pwd?: string) {
|
||||
// const formData = new FormData();
|
||||
// formData.append('content', blobContent);
|
||||
// return formData
|
||||
// }
|
||||
// export async function writeFile(path: string, data: any, pwd?: string) {
|
||||
|
||||
if (path.length < 2) {
|
||||
return false;
|
||||
}
|
||||
path = await resolvePath(path);
|
||||
await fs.writeTextFile(path, data, { baseDir: basedir });
|
||||
return true
|
||||
}
|
||||
export async function appendFile(path: string, data: any) {
|
||||
if (path.length < 2) {
|
||||
return false;
|
||||
}
|
||||
path = await resolvePath(path);
|
||||
return await fs.writeFile(path, data, { baseDir: basedir, append: true });
|
||||
}
|
||||
export function zip(path: string, ext: string) {
|
||||
if (path.length < 2) {
|
||||
return false;
|
||||
}
|
||||
return false
|
||||
}
|
||||
export function unzip(path: string) {
|
||||
if (path.length < 2) {
|
||||
return false;
|
||||
}
|
||||
return false
|
||||
}
|
||||
export function isDesktop(path: string) {
|
||||
const sp = getSp(path)
|
||||
const arr = path.split(sp)
|
||||
return arr[1] === 'C' && arr[2] === 'Users' && arr[3] === 'Desktop' && arr.length === 4
|
||||
}
|
||||
export function join(path: string, ...paths: string[]) {
|
||||
const sp = getSp(path)
|
||||
if (path.endsWith(sp)) {
|
||||
return path + paths.join(sp)
|
||||
} else {
|
||||
return path + sp + paths.join(sp)
|
||||
}
|
||||
}
|
||||
export function basename(path: string): string {
|
||||
const sp = getSp(path)
|
||||
return path.split(sp).pop() || path
|
||||
}
|
||||
export function dirname(path: string): string {
|
||||
const sp = getSp(path)
|
||||
if (path.indexOf(".") > -1) {
|
||||
return path.split(sp).slice(0, -1).join(sp)
|
||||
} else {
|
||||
return path
|
||||
}
|
||||
//return path.split(sp).slice(0, -1).join(sp)
|
||||
}
|
||||
export function getSp(path: string): string {
|
||||
if (path.indexOf("\\") > -1) {
|
||||
return "\\"
|
||||
} else {
|
||||
return "/"
|
||||
}
|
||||
}
|
||||
export function getParentPath(path: string): string {
|
||||
const sp = getSp(path)
|
||||
const arr = path.split(sp);
|
||||
arr.pop();
|
||||
return arr.join(sp);
|
||||
}
|
||||
export function getTopPath(path: string) {
|
||||
const sp = getSp(path)
|
||||
const arr = path.split(sp);
|
||||
if (arr[0] == "") {
|
||||
return arr[1]
|
||||
} else {
|
||||
return arr[0]
|
||||
}
|
||||
}
|
||||
export function getExt(path: string) {
|
||||
return path.split('.').pop() || ''
|
||||
}
|
||||
// if (path.length < 2) {
|
||||
// return false;
|
||||
// }
|
||||
// path = await resolvePath(path);
|
||||
// await fs.writeTextFile(path, data, { baseDir: basedir });
|
||||
// return true
|
||||
// }
|
||||
// export async function appendFile(path: string, data: any) {
|
||||
// if (path.length < 2) {
|
||||
// return false;
|
||||
// }
|
||||
// path = await resolvePath(path);
|
||||
// return await fs.writeFile(path, data, { baseDir: basedir, append: true });
|
||||
// }
|
||||
// export function zip(path: string, ext: string) {
|
||||
// if (path.length < 2) {
|
||||
// return false;
|
||||
// }
|
||||
// return false
|
||||
// }
|
||||
// export function unzip(path: string) {
|
||||
// if (path.length < 2) {
|
||||
// return false;
|
||||
// }
|
||||
// return false
|
||||
// }
|
||||
// export function isDesktop(path: string) {
|
||||
// const sp = getSp(path)
|
||||
// const arr = path.split(sp)
|
||||
// return arr[1] === 'C' && arr[2] === 'Users' && arr[3] === 'Desktop' && arr.length === 4
|
||||
// }
|
||||
// export function join(path: string, ...paths: string[]) {
|
||||
// const sp = getSp(path)
|
||||
// if (path.endsWith(sp)) {
|
||||
// return path + paths.join(sp)
|
||||
// } else {
|
||||
// return path + sp + paths.join(sp)
|
||||
// }
|
||||
// }
|
||||
// export function basename(path: string): string {
|
||||
// const sp = getSp(path)
|
||||
// return path.split(sp).pop() || path
|
||||
// }
|
||||
// export function dirname(path: string): string {
|
||||
// const sp = getSp(path)
|
||||
// if (path.indexOf(".") > -1) {
|
||||
// return path.split(sp).slice(0, -1).join(sp)
|
||||
// } else {
|
||||
// return path
|
||||
// }
|
||||
// //return path.split(sp).slice(0, -1).join(sp)
|
||||
// }
|
||||
// export function getSp(path: string): string {
|
||||
// if (path.indexOf("\\") > -1) {
|
||||
// return "\\"
|
||||
// } else {
|
||||
// return "/"
|
||||
// }
|
||||
// }
|
||||
// export function getParentPath(path: string): string {
|
||||
// const sp = getSp(path)
|
||||
// const arr = path.split(sp);
|
||||
// arr.pop();
|
||||
// return arr.join(sp);
|
||||
// }
|
||||
// export function getTopPath(path: string) {
|
||||
// const sp = getSp(path)
|
||||
// const arr = path.split(sp);
|
||||
// if (arr[0] == "") {
|
||||
// return arr[1]
|
||||
// } else {
|
||||
// return arr[0]
|
||||
// }
|
||||
// }
|
||||
// export function getExt(path: string) {
|
||||
// return path.split('.').pop() || ''
|
||||
// }
|
||||
|
||||
|
||||
@@ -1,106 +1,106 @@
|
||||
import { md5 } from "js-md5";
|
||||
// const token = sign({ id: 1 }, "secret", { expiresIn: "1h" });
|
||||
// console.log(token);
|
||||
// import { md5 } from "js-md5";
|
||||
// // const token = sign({ id: 1 }, "secret", { expiresIn: "1h" });
|
||||
// // console.log(token);
|
||||
|
||||
// try {
|
||||
// const decoded = verify(token, "secret");
|
||||
// console.log(decoded);
|
||||
// } catch (err) {
|
||||
// console.error(err.message); // token 已过期 或 无效的 token
|
||||
// // try {
|
||||
// // const decoded = verify(token, "secret");
|
||||
// // console.log(decoded);
|
||||
// // } catch (err) {
|
||||
// // console.error(err.message); // token 已过期 或 无效的 token
|
||||
// // }
|
||||
// // 支持 expiresIn 参数
|
||||
// export function sign(payload: any, secret: string, options: { expiresIn?: string; refreshExpiresIn?: string } = {}): string {
|
||||
// const { expiresIn = '24h', refreshExpiresIn = '7d' } = options;
|
||||
|
||||
// const now = Math.floor(Date.now() / 1000);
|
||||
// payload.exp = now + parseExpiresIn(expiresIn);
|
||||
// payload.refreshExp = now + parseExpiresIn(refreshExpiresIn);
|
||||
|
||||
// const header = { alg: "HS256", typ: "JWT" };
|
||||
// const base64Header = btoa(JSON.stringify(header));
|
||||
// const base64Payload = btoa(JSON.stringify(payload));
|
||||
// const signature = md5(`${base64Header}.${base64Payload}${secret}`);
|
||||
// return `${base64Header}.${base64Payload}.${signature}`;
|
||||
// }
|
||||
// 支持 expiresIn 参数
|
||||
export function sign(payload: any, secret: string, options: { expiresIn?: string; refreshExpiresIn?: string } = {}): string {
|
||||
const { expiresIn = '24h', refreshExpiresIn = '7d' } = options;
|
||||
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
payload.exp = now + parseExpiresIn(expiresIn);
|
||||
payload.refreshExp = now + parseExpiresIn(refreshExpiresIn);
|
||||
// export function verify(token: string, secret: string): any {
|
||||
// const [base64Header, base64Payload, signature] = token.split(".");
|
||||
// const expectedSignature = md5(`${base64Header}.${base64Payload}${secret}`);
|
||||
|
||||
const header = { alg: "HS256", typ: "JWT" };
|
||||
const base64Header = btoa(JSON.stringify(header));
|
||||
const base64Payload = btoa(JSON.stringify(payload));
|
||||
const signature = md5(`${base64Header}.${base64Payload}${secret}`);
|
||||
return `${base64Header}.${base64Payload}.${signature}`;
|
||||
}
|
||||
// if (signature !== expectedSignature) {
|
||||
// throw new Error("无效的 token");
|
||||
// }
|
||||
|
||||
export function verify(token: string, secret: string): any {
|
||||
const [base64Header, base64Payload, signature] = token.split(".");
|
||||
const expectedSignature = md5(`${base64Header}.${base64Payload}${secret}`);
|
||||
// const decodedPayload = JSON.parse(atob(base64Payload));
|
||||
|
||||
if (signature !== expectedSignature) {
|
||||
throw new Error("无效的 token");
|
||||
}
|
||||
// const now = Math.floor(Date.now() / 1000);
|
||||
// if (decodedPayload.exp && decodedPayload.exp < now) {
|
||||
// throw new Error("token 已过期");
|
||||
// }
|
||||
|
||||
const decodedPayload = JSON.parse(atob(base64Payload));
|
||||
// return decodedPayload;
|
||||
// }
|
||||
// export function verifyWithRefresh(token: string, secret: string, options: { expiresIn?: string } = {}): { success: boolean, token: string | null } {
|
||||
// try {
|
||||
// verify(token, secret);
|
||||
// return { success: true, token: token }; // 未过期,无需刷新
|
||||
// } catch (err: any) {
|
||||
// if (err.message === "token 已过期") {
|
||||
// try {
|
||||
// // 尝试刷新 token
|
||||
// const newToken = refreshToken(token, secret, options);
|
||||
// return { success: true, token: newToken }; // 刷新成功
|
||||
// } catch (refreshErr: any) {
|
||||
// if (refreshErr.message === "刷新 token 已过期") {
|
||||
// return { success: false, token: null }; // refresh token 也过期了
|
||||
// }
|
||||
// return { success: false, token: null }; // 其他错误
|
||||
// }
|
||||
// } else {
|
||||
// return { success: false, token: null }; // 校验失败(签名错误等)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// export function refreshToken(oldToken: string, secret: string, options: { expiresIn?: string } = {}): string {
|
||||
// const decoded = verifyRefreshToken(oldToken, secret);
|
||||
// const newPayload = { id: decoded.id }; // 可根据需要提取更多字段
|
||||
// return sign(newPayload, secret, options);
|
||||
// }
|
||||
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
if (decodedPayload.exp && decodedPayload.exp < now) {
|
||||
throw new Error("token 已过期");
|
||||
}
|
||||
// function verifyRefreshToken(token: string, secret: string): any {
|
||||
// const decoded = verify(token, secret);
|
||||
|
||||
return decodedPayload;
|
||||
}
|
||||
export function verifyWithRefresh(token: string, secret: string, options: { expiresIn?: string } = {}): { success: boolean, token: string | null } {
|
||||
try {
|
||||
verify(token, secret);
|
||||
return { success: true, token: token }; // 未过期,无需刷新
|
||||
} catch (err: any) {
|
||||
if (err.message === "token 已过期") {
|
||||
try {
|
||||
// 尝试刷新 token
|
||||
const newToken = refreshToken(token, secret, options);
|
||||
return { success: true, token: newToken }; // 刷新成功
|
||||
} catch (refreshErr: any) {
|
||||
if (refreshErr.message === "刷新 token 已过期") {
|
||||
return { success: false, token: null }; // refresh token 也过期了
|
||||
}
|
||||
return { success: false, token: null }; // 其他错误
|
||||
}
|
||||
} else {
|
||||
return { success: false, token: null }; // 校验失败(签名错误等)
|
||||
}
|
||||
}
|
||||
}
|
||||
export function refreshToken(oldToken: string, secret: string, options: { expiresIn?: string } = {}): string {
|
||||
const decoded = verifyRefreshToken(oldToken, secret);
|
||||
const newPayload = { id: decoded.id }; // 可根据需要提取更多字段
|
||||
return sign(newPayload, secret, options);
|
||||
}
|
||||
// const now = Math.floor(Date.now() / 1000);
|
||||
// if (!decoded.refreshExp || decoded.refreshExp < now) {
|
||||
// throw new Error("刷新 token 已过期");
|
||||
// }
|
||||
|
||||
function verifyRefreshToken(token: string, secret: string): any {
|
||||
const decoded = verify(token, secret);
|
||||
// return decoded;
|
||||
// }
|
||||
// function parseExpiresIn(expiresIn: string): number {
|
||||
// const regex = /^(\d+)([smhdw])$/;
|
||||
// const match = expiresIn.match(regex);
|
||||
// if (!match) throw new Error("Invalid expiresIn format");
|
||||
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
if (!decoded.refreshExp || decoded.refreshExp < now) {
|
||||
throw new Error("刷新 token 已过期");
|
||||
}
|
||||
// const value = parseInt(match[1], 10);
|
||||
// const unit = match[2];
|
||||
|
||||
return decoded;
|
||||
}
|
||||
function parseExpiresIn(expiresIn: string): number {
|
||||
const regex = /^(\d+)([smhdw])$/;
|
||||
const match = expiresIn.match(regex);
|
||||
if (!match) throw new Error("Invalid expiresIn format");
|
||||
// switch (unit) {
|
||||
// case 's': return value;
|
||||
// case 'm': return value * 60;
|
||||
// case 'h': return value * 3600;
|
||||
// case 'd': return value * 86400;
|
||||
// case 'w': return value * 604800;
|
||||
// default: throw new Error("Unknown time unit");
|
||||
// }
|
||||
// }
|
||||
|
||||
const value = parseInt(match[1], 10);
|
||||
const unit = match[2];
|
||||
|
||||
switch (unit) {
|
||||
case 's': return value;
|
||||
case 'm': return value * 60;
|
||||
case 'h': return value * 3600;
|
||||
case 'd': return value * 86400;
|
||||
case 'w': return value * 604800;
|
||||
default: throw new Error("Unknown time unit");
|
||||
}
|
||||
}
|
||||
|
||||
export function generate16BitString(): string {
|
||||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||||
let result = '';
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const randomIndex = Math.floor(Math.random() * chars.length);
|
||||
result += chars.charAt(randomIndex);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
// export function generate16BitString(): string {
|
||||
// const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||||
// let result = '';
|
||||
// for (let i = 0; i < 16; i++) {
|
||||
// const randomIndex = Math.floor(Math.random() * chars.length);
|
||||
// result += chars.charAt(randomIndex);
|
||||
// }
|
||||
// return result;
|
||||
// }
|
||||
+174
-174
@@ -1,189 +1,189 @@
|
||||
import * as files from './files'
|
||||
import * as fs from '@tauri-apps/plugin-fs'
|
||||
import * as ps from '@tauri-apps/api/path';
|
||||
interface OsFileInfo {
|
||||
Name: string;
|
||||
Path: string;
|
||||
OldPath: string;
|
||||
ParentPath: string;
|
||||
Content: string;
|
||||
Ext: string;
|
||||
Title: string;
|
||||
ID: number;
|
||||
IsFile: boolean;
|
||||
IsDir: boolean;
|
||||
IsSymlink: boolean;
|
||||
Size: number;
|
||||
ModTime: Date;
|
||||
AccessTime: Date;
|
||||
CreateTime: Date;
|
||||
Mode: number;
|
||||
}
|
||||
// import * as files from './files'
|
||||
// import * as fs from '@tauri-apps/plugin-fs'
|
||||
// import * as ps from '@tauri-apps/api/path';
|
||||
// interface OsFileInfo {
|
||||
// Name: string;
|
||||
// Path: string;
|
||||
// OldPath: string;
|
||||
// ParentPath: string;
|
||||
// Content: string;
|
||||
// Ext: string;
|
||||
// Title: string;
|
||||
// ID: number;
|
||||
// IsFile: boolean;
|
||||
// IsDir: boolean;
|
||||
// IsSymlink: boolean;
|
||||
// Size: number;
|
||||
// ModTime: Date;
|
||||
// AccessTime: Date;
|
||||
// CreateTime: Date;
|
||||
// Mode: number;
|
||||
// }
|
||||
|
||||
interface RootObject {
|
||||
UpdateTime: Date;
|
||||
Desktop: OsFileInfo[];
|
||||
Menulist: OsFileInfo[];
|
||||
}
|
||||
const RootAppList = [
|
||||
{ name: "computer", icon: "diannao", position: "Desktop,Menulist" },
|
||||
{ name: "appstore", icon: "store", position: "Desktop,Menulist" },
|
||||
{ name: "localchat", icon: "chat", position: "Desktop" },
|
||||
{ name: "document", icon: "word", position: "Desktop" },
|
||||
{ name: "excel", icon: "excel", position: "Desktop" },
|
||||
{ name: "markdown", icon: "markdown", position: "Desktop" },
|
||||
{ name: "mindmap", icon: "mindexe", position: "Desktop" },
|
||||
{ name: "ppt", icon: "pptexe", position: "Desktop" },
|
||||
{ name: "fileEditor", icon: "editorbt", position: "Desktop" },
|
||||
{ name: "board", icon: "kanban", position: "Desktop" },
|
||||
{ name: "whiteBoard", icon: "baiban", position: "Desktop" },
|
||||
{ name: "piceditor", icon: "picedit", position: "Desktop" },
|
||||
{ name: "gantt", icon: "gant", position: "Desktop" },
|
||||
{ name: "browser", icon: "brower", position: "Desktop,Menulist" },
|
||||
{ name: "setting", icon: "setting", position: "Menulist" },
|
||||
{ name: "system.version", icon: "info", position: "Menulist" },
|
||||
{ name: "process.title", icon: "progress", position: "Menulist" },
|
||||
{ name: "calculator", icon: "calculator", position: "Menulist" },
|
||||
{ name: "calendar", icon: "calendar", position: "Menulist" },
|
||||
{ name: "musicStore", icon: "music", position: "Menulist" },
|
||||
{ name: "gallery", icon: "gallery", position: "Menulist" },
|
||||
{ name: "aiHelper", icon: "aiassistant", position: "Desktop" },
|
||||
{ name: "aiModule", icon: "aidown", position: "Desktop" },
|
||||
{ name: "aiSetting", icon: "aisetting", position: "Menulist" },
|
||||
];
|
||||
const InitPaths = [
|
||||
'Desktop',
|
||||
'Menulist',
|
||||
'Documents',
|
||||
'Downloads',
|
||||
'Music',
|
||||
'Pictures',
|
||||
'Videos',
|
||||
'Schedule',
|
||||
'Reciv',
|
||||
];
|
||||
const InitDocPath = [
|
||||
'Word',
|
||||
'Markdown',
|
||||
'PPT',
|
||||
'Baiban',
|
||||
'Kanban',
|
||||
'Excel',
|
||||
'Mind',
|
||||
'Screenshot',
|
||||
'ScreenRecording',
|
||||
];
|
||||
export async function initOsSystem(): Promise<void> {
|
||||
try {
|
||||
const basePath = await files.appPath(); // 需要你自己实现 libs.getOsDir()
|
||||
console.log(basePath)
|
||||
const osCpath = await ps.join(basePath, 'C');
|
||||
// interface RootObject {
|
||||
// UpdateTime: Date;
|
||||
// Desktop: OsFileInfo[];
|
||||
// Menulist: OsFileInfo[];
|
||||
// }
|
||||
// const RootAppList = [
|
||||
// { name: "computer", icon: "diannao", position: "Desktop,Menulist" },
|
||||
// { name: "appstore", icon: "store", position: "Desktop,Menulist" },
|
||||
// { name: "localchat", icon: "chat", position: "Desktop" },
|
||||
// { name: "document", icon: "word", position: "Desktop" },
|
||||
// { name: "excel", icon: "excel", position: "Desktop" },
|
||||
// { name: "markdown", icon: "markdown", position: "Desktop" },
|
||||
// { name: "mindmap", icon: "mindexe", position: "Desktop" },
|
||||
// { name: "ppt", icon: "pptexe", position: "Desktop" },
|
||||
// { name: "fileEditor", icon: "editorbt", position: "Desktop" },
|
||||
// { name: "board", icon: "kanban", position: "Desktop" },
|
||||
// { name: "whiteBoard", icon: "baiban", position: "Desktop" },
|
||||
// { name: "piceditor", icon: "picedit", position: "Desktop" },
|
||||
// { name: "gantt", icon: "gant", position: "Desktop" },
|
||||
// { name: "browser", icon: "brower", position: "Desktop,Menulist" },
|
||||
// { name: "setting", icon: "setting", position: "Menulist" },
|
||||
// { name: "system.version", icon: "info", position: "Menulist" },
|
||||
// { name: "process.title", icon: "progress", position: "Menulist" },
|
||||
// { name: "calculator", icon: "calculator", position: "Menulist" },
|
||||
// { name: "calendar", icon: "calendar", position: "Menulist" },
|
||||
// { name: "musicStore", icon: "music", position: "Menulist" },
|
||||
// { name: "gallery", icon: "gallery", position: "Menulist" },
|
||||
// { name: "aiHelper", icon: "aiassistant", position: "Desktop" },
|
||||
// { name: "aiModule", icon: "aidown", position: "Desktop" },
|
||||
// { name: "aiSetting", icon: "aisetting", position: "Menulist" },
|
||||
// ];
|
||||
// const InitPaths = [
|
||||
// 'Desktop',
|
||||
// 'Menulist',
|
||||
// 'Documents',
|
||||
// 'Downloads',
|
||||
// 'Music',
|
||||
// 'Pictures',
|
||||
// 'Videos',
|
||||
// 'Schedule',
|
||||
// 'Reciv',
|
||||
// ];
|
||||
// const InitDocPath = [
|
||||
// 'Word',
|
||||
// 'Markdown',
|
||||
// 'PPT',
|
||||
// 'Baiban',
|
||||
// 'Kanban',
|
||||
// 'Excel',
|
||||
// 'Mind',
|
||||
// 'Screenshot',
|
||||
// 'ScreenRecording',
|
||||
// ];
|
||||
// export async function initOsSystem(): Promise<void> {
|
||||
// try {
|
||||
// const basePath = await files.appPath(); // 需要你自己实现 libs.getOsDir()
|
||||
// console.log(basePath)
|
||||
// const osCpath = await ps.join(basePath, 'C');
|
||||
|
||||
if (!(await fs.exists(osCpath))) {
|
||||
await fs.mkdir(osCpath, { recursive: true });
|
||||
}
|
||||
// if (!(await fs.exists(osCpath))) {
|
||||
// await fs.mkdir(osCpath, { recursive: true });
|
||||
// }
|
||||
|
||||
const baseOsDir = ['D', 'E', 'B'];
|
||||
for (const dir of baseOsDir) {
|
||||
const dirPath = await ps.join(basePath, dir);
|
||||
if (!(await fs.exists(dirPath))) {
|
||||
await fs.mkdir(dirPath, { recursive: true });
|
||||
}
|
||||
}
|
||||
// const baseOsDir = ['D', 'E', 'B'];
|
||||
// for (const dir of baseOsDir) {
|
||||
// const dirPath = await ps.join(basePath, dir);
|
||||
// if (!(await fs.exists(dirPath))) {
|
||||
// await fs.mkdir(dirPath, { recursive: true });
|
||||
// }
|
||||
// }
|
||||
|
||||
const systemPath = await ps.join(osCpath, 'System');
|
||||
if (!(await fs.exists(systemPath))) {
|
||||
await fs.mkdir(systemPath, { recursive: true });
|
||||
}
|
||||
// const systemPath = await ps.join(osCpath, 'System');
|
||||
// if (!(await fs.exists(systemPath))) {
|
||||
// await fs.mkdir(systemPath, { recursive: true });
|
||||
// }
|
||||
|
||||
const userPath = await ps.join(osCpath, 'Users');
|
||||
if (!(await fs.exists(userPath))) {
|
||||
await fs.mkdir(userPath, { recursive: true });
|
||||
for (const dir of InitPaths) {
|
||||
const dirPath = await ps.join(userPath, dir);
|
||||
if (!(await fs.exists(dirPath))) {
|
||||
await fs.mkdir(dirPath, { recursive: true });
|
||||
}
|
||||
}
|
||||
const docpath = await ps.join(userPath, 'Documents');
|
||||
for (const dir of InitDocPath) {
|
||||
const dirPath = await ps.join(docpath, dir);
|
||||
if (!(await fs.exists(dirPath))) {
|
||||
await fs.mkdir(dirPath, { recursive: true });
|
||||
}
|
||||
}
|
||||
// const userPath = await ps.join(osCpath, 'Users');
|
||||
// if (!(await fs.exists(userPath))) {
|
||||
// await fs.mkdir(userPath, { recursive: true });
|
||||
// for (const dir of InitPaths) {
|
||||
// const dirPath = await ps.join(userPath, dir);
|
||||
// if (!(await fs.exists(dirPath))) {
|
||||
// await fs.mkdir(dirPath, { recursive: true });
|
||||
// }
|
||||
// }
|
||||
// const docpath = await ps.join(userPath, 'Documents');
|
||||
// for (const dir of InitDocPath) {
|
||||
// const dirPath = await ps.join(docpath, dir);
|
||||
// if (!(await fs.exists(dirPath))) {
|
||||
// await fs.mkdir(dirPath, { recursive: true });
|
||||
// }
|
||||
// }
|
||||
|
||||
const applist = getInitRootList();
|
||||
const desktopPath = await ps.join(userPath, 'Desktop');
|
||||
for (const app of applist.Desktop) {
|
||||
const appPath = await ps.join(desktopPath, app.Name);
|
||||
if (!(await fs.exists(appPath))) {
|
||||
await fs.writeFile(appPath, new TextEncoder().encode(app.Content));
|
||||
}
|
||||
}
|
||||
// const applist = getInitRootList();
|
||||
// const desktopPath = await ps.join(userPath, 'Desktop');
|
||||
// for (const app of applist.Desktop) {
|
||||
// const appPath = await ps.join(desktopPath, app.Name);
|
||||
// if (!(await fs.exists(appPath))) {
|
||||
// await fs.writeFile(appPath, new TextEncoder().encode(app.Content));
|
||||
// }
|
||||
// }
|
||||
|
||||
const menulistPath = await ps.join(userPath, 'Menulist');
|
||||
for (const app of applist.Menulist) {
|
||||
const appPath = await ps.join(menulistPath, app.Name);
|
||||
if (!(await fs.exists(appPath))) {
|
||||
await fs.writeFile(appPath, new TextEncoder().encode(app.Content));
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
throw new Error(`InitOsSystem error: ${err}`);
|
||||
}
|
||||
}
|
||||
// const menulistPath = await ps.join(userPath, 'Menulist');
|
||||
// for (const app of applist.Menulist) {
|
||||
// const appPath = await ps.join(menulistPath, app.Name);
|
||||
// if (!(await fs.exists(appPath))) {
|
||||
// await fs.writeFile(appPath, new TextEncoder().encode(app.Content));
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// } catch (err) {
|
||||
// throw new Error(`InitOsSystem error: ${err}`);
|
||||
// }
|
||||
// }
|
||||
|
||||
|
||||
|
||||
function getInitRootList(): RootObject {
|
||||
const nowtime = new Date();
|
||||
let id = 1;
|
||||
// function getInitRootList(): RootObject {
|
||||
// const nowtime = new Date();
|
||||
// let id = 1;
|
||||
|
||||
const desktopApps: OsFileInfo[] = [];
|
||||
const menulistApps: OsFileInfo[] = [];
|
||||
// const desktopApps: OsFileInfo[] = [];
|
||||
// const menulistApps: OsFileInfo[] = [];
|
||||
|
||||
for (const app of RootAppList) {
|
||||
const positions = app.position.split(",");
|
||||
const content = `link::Desktop::${app.name}::${app.icon}`;
|
||||
// for (const app of RootAppList) {
|
||||
// const positions = app.position.split(",");
|
||||
// const content = `link::Desktop::${app.name}::${app.icon}`;
|
||||
|
||||
for (const pos of positions) {
|
||||
const baseProps = {
|
||||
Name: `${app.name}.exe`,
|
||||
OldPath: `/C/Users/${pos}/${app.name}.exe`,
|
||||
ParentPath: `/C/Users/${pos}`,
|
||||
Content: content,
|
||||
Ext: "exe",
|
||||
Title: app.name,
|
||||
ID: id++,
|
||||
IsFile: true,
|
||||
IsDir: false,
|
||||
IsSymlink: false,
|
||||
Size: content.length,
|
||||
ModTime: nowtime,
|
||||
AccessTime: nowtime,
|
||||
CreateTime: nowtime,
|
||||
Mode: 511,
|
||||
};
|
||||
// for (const pos of positions) {
|
||||
// const baseProps = {
|
||||
// Name: `${app.name}.exe`,
|
||||
// OldPath: `/C/Users/${pos}/${app.name}.exe`,
|
||||
// ParentPath: `/C/Users/${pos}`,
|
||||
// Content: content,
|
||||
// Ext: "exe",
|
||||
// Title: app.name,
|
||||
// ID: id++,
|
||||
// IsFile: true,
|
||||
// IsDir: false,
|
||||
// IsSymlink: false,
|
||||
// Size: content.length,
|
||||
// ModTime: nowtime,
|
||||
// AccessTime: nowtime,
|
||||
// CreateTime: nowtime,
|
||||
// Mode: 511,
|
||||
// };
|
||||
|
||||
if (pos === "Desktop") {
|
||||
desktopApps.push({
|
||||
...baseProps,
|
||||
Path: `/C/Users/Desktop/${app.name}.exe`,
|
||||
});
|
||||
} else if (pos === "Menulist") {
|
||||
menulistApps.push({
|
||||
...baseProps,
|
||||
Path: `/C/Users/Menulist/${app.name}.exe`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// if (pos === "Desktop") {
|
||||
// desktopApps.push({
|
||||
// ...baseProps,
|
||||
// Path: `/C/Users/Desktop/${app.name}.exe`,
|
||||
// });
|
||||
// } else if (pos === "Menulist") {
|
||||
// menulistApps.push({
|
||||
// ...baseProps,
|
||||
// Path: `/C/Users/Menulist/${app.name}.exe`,
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
return {
|
||||
UpdateTime: nowtime,
|
||||
Desktop: desktopApps,
|
||||
Menulist: menulistApps,
|
||||
};
|
||||
}
|
||||
// return {
|
||||
// UpdateTime: nowtime,
|
||||
// Desktop: desktopApps,
|
||||
// Menulist: menulistApps,
|
||||
// };
|
||||
// }
|
||||
@@ -1,6 +1,6 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, Ref, computed } from 'vue'
|
||||
import { Files } from '@/api/files'
|
||||
import * as fs from '@/api/net/files'
|
||||
import { useLoginStore } from './login'
|
||||
|
||||
export const useDesktopStore = defineStore('desktop', () => {
|
||||
@@ -26,7 +26,6 @@ export const useDesktopStore = defineStore('desktop', () => {
|
||||
const isStartMenuOpen: Ref<boolean> = ref(false)
|
||||
const screenshotStatus: Ref<boolean> = ref(false)
|
||||
const initDesktop = async () => {
|
||||
const fs = await Files()
|
||||
const res: any = await fs.desktop()
|
||||
if (!res) {
|
||||
loginStore.isLoginState = false
|
||||
|
||||
+27
-26
@@ -1,4 +1,5 @@
|
||||
import {Files} from '@/api/files';
|
||||
// import {Files} from '@/api/files';
|
||||
import * as fs from '@/api/net/files'
|
||||
import { joinknowledge } from '@/api/net/knowledge';
|
||||
import { shareCreate } from "@/api/net/share";
|
||||
import { eventBus } from '@/interfaces/event';
|
||||
@@ -51,7 +52,7 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
const getFilesInPath = async (path: string, pwd?: string) => {
|
||||
currentPath.value = path;
|
||||
setPwdPathMap(path, pwd);
|
||||
const fs = await Files();
|
||||
|
||||
const res = await fs.read(path, getPwdPathMap(path));
|
||||
if (!res.success) {
|
||||
pwd = await promptPwd();
|
||||
@@ -72,7 +73,7 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
currentPath.value = path;
|
||||
}
|
||||
const getUniqueFilePath = async (filePath: string, defname: string, ext: string, path: string, sp: string, i: number): Promise<string> => {
|
||||
const fs = await Files();
|
||||
|
||||
const isExits = await fs.exists(filePath);
|
||||
//console.log(isExits)
|
||||
if (isExits) {
|
||||
@@ -82,7 +83,7 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
};
|
||||
const getUniquePath = async (path: string): Promise<string> => {
|
||||
const sp = path.charAt(0);
|
||||
const fs = await Files();
|
||||
|
||||
const baseName = fs.basename(path);
|
||||
const arr = baseName.split('.');
|
||||
//console.log(arr)
|
||||
@@ -101,13 +102,13 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
let newFilePath = `${path}${sp}${defname}${ext}`;
|
||||
newFilePath = await getUniqueFilePath(newFilePath, defname, ext, path, sp, 1);
|
||||
//console.log(newFilePath);
|
||||
const fs = await Files();
|
||||
|
||||
await fs.writeFile(newFilePath, '');
|
||||
refreshPaths()
|
||||
}
|
||||
const handleReadFile = async (filePath: string, pwd?: string) => {
|
||||
setPwdPathMap(filePath, pwd);
|
||||
const fs = await Files();
|
||||
|
||||
const res = await fs.readFile(filePath, getPwdPathMap(filePath));
|
||||
console.log(res);
|
||||
if (!res.success) {
|
||||
@@ -128,7 +129,7 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
const handlePwdFile = async (path: string) => {
|
||||
const pwd = await promptPwd();
|
||||
if (!pwd) return;
|
||||
const fs = await Files();
|
||||
|
||||
const res = await fs.pwd(path, pwd);
|
||||
refreshPaths()
|
||||
return res;
|
||||
@@ -136,7 +137,7 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
const handleUnpwdFile = async (filePath: string) => {
|
||||
const pwd = await promptPwd();
|
||||
if (!pwd) return;
|
||||
const fs = await Files();
|
||||
|
||||
const res = await fs.unpwd(filePath, pwd);
|
||||
refreshPaths()
|
||||
return res;
|
||||
@@ -144,7 +145,7 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
const handleWriteFile = async (filePath: string, data: any, pwd?: string) => {
|
||||
//console.log('data:', data)
|
||||
setPwdPathMap(filePath, pwd);
|
||||
const fs = await Files();
|
||||
|
||||
let res = await fs.writeFile(filePath, data, getPwdPathMap(filePath));
|
||||
if (!res) {
|
||||
const pwd = await promptPwd();
|
||||
@@ -160,19 +161,19 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
}
|
||||
|
||||
const handleSerach = async (path: string, query: string) => {
|
||||
const fs = await Files();
|
||||
|
||||
const res = await fs.search(path, query);
|
||||
return res || [];
|
||||
}
|
||||
const handleDeleteFile = async (path: string) => {
|
||||
if (!path) return;
|
||||
const fs = await Files();
|
||||
|
||||
await fs.rmdir(path)
|
||||
//console.log(dirname(path))
|
||||
refreshPaths()
|
||||
}
|
||||
const handleDeleteFiles = async (filePaths: string[]) => {
|
||||
const fs = await Files();
|
||||
|
||||
for (const filePath of filePaths) {
|
||||
await fs.rmdir(filePath)
|
||||
}
|
||||
@@ -183,7 +184,7 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
//console.log(path)
|
||||
const sp = path.charAt(0);
|
||||
let newDirPath = `${path}${sp}${dirname}`;
|
||||
const fs = await Files();
|
||||
|
||||
newDirPath = await getUniqueFilePath(`${newDirPath}`, dirname, '', path, sp, 1);
|
||||
await fs.mkdir(newDirPath);
|
||||
refreshPaths()
|
||||
@@ -191,7 +192,7 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
const handleRenameFile = async (oldPath: string) => {
|
||||
if (!oldPath) return;
|
||||
//const sp = oldPath.charAt(0);
|
||||
const fs = await Files();
|
||||
|
||||
const oldName = fs.basename(oldPath);
|
||||
const newName = await promptMsg('请输入新文件名', '重命名', oldName);
|
||||
//console.log(newName)
|
||||
@@ -237,7 +238,7 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
}
|
||||
}
|
||||
const openFile = async (file: any) => {
|
||||
const fs = await Files();
|
||||
|
||||
if (typeof file == 'string') {
|
||||
const f = await fs.stat(file)
|
||||
await openfile(f)
|
||||
@@ -253,7 +254,7 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
openFile(file)
|
||||
}
|
||||
const moveFiles = async (filePaths: string[], targetPath: string) => {
|
||||
const fs = await Files();
|
||||
|
||||
const toFile = await fs.stat(targetPath);
|
||||
if (toFile?.isDirectory) {
|
||||
for (const filePath of filePaths) {
|
||||
@@ -268,7 +269,7 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
}
|
||||
}
|
||||
const copyFiles = async (filePaths: string[], targetPath: string) => {
|
||||
const fs = await Files();
|
||||
|
||||
const toFile = await fs.stat(targetPath);
|
||||
if (toFile?.isDirectory) {
|
||||
for (const filePath of filePaths) {
|
||||
@@ -280,23 +281,23 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
}
|
||||
}
|
||||
const handleUnzipFile = async (filePath: string) => {
|
||||
const fs = await Files();
|
||||
|
||||
await fs.unzip(filePath);
|
||||
refreshPaths()
|
||||
}
|
||||
const handleFavorite = async (filePath: string) => {
|
||||
const fs = await Files();
|
||||
|
||||
await fs.favorite(filePath);
|
||||
refreshPaths()
|
||||
}
|
||||
const handleZipFile = async (filePath: string, ext: string) => {
|
||||
const fs = await Files();
|
||||
|
||||
await fs.zip(filePath, ext);
|
||||
refreshPaths()
|
||||
noticeMsg('压缩成功');
|
||||
}
|
||||
const handleFileStat = async (filePath: string) => {
|
||||
const fs = await Files();
|
||||
|
||||
return await fs.stat(filePath);
|
||||
}
|
||||
const chooseFiles = (exts: string[] = []) => {
|
||||
@@ -353,11 +354,11 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
choose.value = { ...initChoose };
|
||||
}
|
||||
const parserFormData = async (content: any, contentType: any) => {
|
||||
const fs = await Files();
|
||||
|
||||
return fs.parserFormData(content, contentType);
|
||||
}
|
||||
const reStoreFiles = async (dirPath: string) => {
|
||||
const fs = await Files();
|
||||
|
||||
await fs.restore(dirPath);
|
||||
refreshPaths()
|
||||
}
|
||||
@@ -403,7 +404,7 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
}
|
||||
async function onFileSelected(list: any) {
|
||||
if (!list) return;
|
||||
const fs = await Files();
|
||||
|
||||
const len = list.length
|
||||
const path = fs.dirname(currentPath.value);
|
||||
for (let i = 0; i < len; i++) {
|
||||
@@ -450,7 +451,7 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
const fs = await Files();
|
||||
|
||||
a.download = fs.basename(filePath);
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
@@ -467,7 +468,7 @@ export const useFileSystemStore = defineStore('filesystem', () => {
|
||||
currentPath,
|
||||
choose,
|
||||
currentShareFile,
|
||||
fs:Files,
|
||||
fs,
|
||||
initFolder,
|
||||
getFilesInPath,
|
||||
getUniquePath,
|
||||
|
||||
@@ -2,8 +2,9 @@ import { defineStore } from "pinia";
|
||||
import { ref } from "vue";
|
||||
import { systemSettingList, settingsConfig } from "@/stores/settingsConfig";
|
||||
import { md5 } from "js-md5";
|
||||
import { getPlatformInfo } from "@/utils/device";
|
||||
import { initDatabase } from "@/api/local/orm/db";
|
||||
import { isMobileDevice } from "@/utils/device";
|
||||
|
||||
//import { initDatabase } from "@/api/local/orm/db";
|
||||
export const useSettingsStore = defineStore('settings', () => {
|
||||
const settingList = ref(systemSettingList);
|
||||
|
||||
@@ -49,11 +50,11 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||
* 初始化操作系统相关信息
|
||||
*/
|
||||
const osInit = async () => {
|
||||
systemInfo.value = getPlatformInfo();
|
||||
console.log(systemInfo.value)
|
||||
if (!systemInfo.value.isWeb) {
|
||||
await initDatabase();
|
||||
}
|
||||
// systemInfo.value = getPlatformInfo();
|
||||
// console.log(systemInfo.value)
|
||||
// if (!systemInfo.value.isWeb) {
|
||||
// await initDatabase();
|
||||
// }
|
||||
}
|
||||
return {
|
||||
settingList,
|
||||
|
||||
+27
-27
@@ -1,4 +1,4 @@
|
||||
import { type as osType, platform } from "@tauri-apps/plugin-os";
|
||||
// import { type as osType, platform } from "@tauri-apps/plugin-os";
|
||||
export const isMobileDevice = () => {
|
||||
const userAgent = navigator.userAgent.toLowerCase();
|
||||
const mobileKeywords = ['iphone', 'android', 'mobile', 'blackberry', 'iemobile', 'opera mini'];
|
||||
@@ -9,29 +9,29 @@ export const isMobileDevice = () => {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
export const getPlatformInfo = () => {
|
||||
const info = {
|
||||
platform: "web",
|
||||
ostype: "web",
|
||||
isMobile: false,
|
||||
isDesktop: false,
|
||||
isWeb: true,
|
||||
};
|
||||
try {
|
||||
info.platform = platform();
|
||||
}
|
||||
catch (error) {
|
||||
info.platform = "web";
|
||||
}
|
||||
try {
|
||||
info.ostype = osType();
|
||||
}
|
||||
catch (error) {
|
||||
// console.warn(error);
|
||||
info.ostype = "web";
|
||||
}
|
||||
info.isMobile = ["android", "ios"].includes(info.ostype);
|
||||
info.isWeb = info.platform === "web";
|
||||
info.isDesktop = !info.isMobile && !info.isWeb;
|
||||
return info;
|
||||
}
|
||||
// export const getPlatformInfo = () => {
|
||||
// const info = {
|
||||
// platform: "web",
|
||||
// ostype: "web",
|
||||
// isMobile: false,
|
||||
// isDesktop: false,
|
||||
// isWeb: true,
|
||||
// };
|
||||
// try {
|
||||
// info.platform = platform();
|
||||
// }
|
||||
// catch (error) {
|
||||
// info.platform = "web";
|
||||
// }
|
||||
// try {
|
||||
// info.ostype = osType();
|
||||
// }
|
||||
// catch (error) {
|
||||
// // console.warn(error);
|
||||
// info.ostype = "web";
|
||||
// }
|
||||
// info.isMobile = ["android", "ios"].includes(info.ostype);
|
||||
// info.isWeb = info.platform === "web";
|
||||
// info.isDesktop = !info.isMobile && !info.isWeb;
|
||||
// return info;
|
||||
// }
|
||||
@@ -0,0 +1,16 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"godocms/middleware"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func init() {
|
||||
middleware.RegisterRouter("POST", "/api/v1/test", test, 0, "test")
|
||||
}
|
||||
func test(c *gin.Context) {
|
||||
c.JSON(200, gin.H{
|
||||
"msg": "hello",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
_ "godocms/app/admin"
|
||||
_ "godocms/app/user"
|
||||
)
|
||||
@@ -0,0 +1 @@
|
||||
package user
|
||||
@@ -0,0 +1,109 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "godocms/app"
|
||||
"godocms/config"
|
||||
"godocms/middleware"
|
||||
"godocms/pkg/dbfactory"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
var Server *http.Server
|
||||
|
||||
func Start() {
|
||||
dbfactory.InitDatabase()
|
||||
config.LoadConfig()
|
||||
handler, err := config.InitLogger()
|
||||
if err != nil {
|
||||
slog.Error("Failed to initialize logger:", "error", err)
|
||||
}
|
||||
|
||||
if config.Config.System.Debug {
|
||||
gin.SetMode(gin.DebugMode)
|
||||
} else {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
}
|
||||
r := gin.Default()
|
||||
|
||||
// 处理异常
|
||||
r.NoRoute(middleware.HandleNotFound)
|
||||
r.NoMethod(middleware.HandleNotFound)
|
||||
r.Use(middleware.Recover)
|
||||
|
||||
// 使用中间件
|
||||
r.Use(middleware.Cors())
|
||||
r.Use(middleware.LoggerMiddleware(handler))
|
||||
store := middleware.GetSessionStore()
|
||||
r.Use(sessions.Sessions("godoSession", store))
|
||||
middleware.BindRouter(r)
|
||||
// 将端口号转换为字符串
|
||||
portStr := strconv.Itoa(config.Config.System.Port)
|
||||
|
||||
// 创建并返回 http.Server 实例
|
||||
Server = &http.Server{
|
||||
Addr: ":" + portStr,
|
||||
Handler: r,
|
||||
}
|
||||
go func() {
|
||||
if err := Server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
slog.Error("Failed to start server:", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}()
|
||||
// 监听信号来重启服务
|
||||
sigChan := make(chan os.Signal, 1)
|
||||
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
|
||||
|
||||
go func() {
|
||||
for sig := range sigChan {
|
||||
switch sig {
|
||||
case os.Interrupt, syscall.SIGTERM:
|
||||
slog.Info("Received SIGTERM or SIGINT, shutting down...")
|
||||
Shutdown()
|
||||
os.Exit(0)
|
||||
case syscall.SIGHUP:
|
||||
slog.Info("Received SIGHUP, restarting...")
|
||||
Restart()
|
||||
default:
|
||||
slog.Info("Received unknown signal:", "signal", sig)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// 主循环
|
||||
select {}
|
||||
}
|
||||
func Restart() {
|
||||
if Server == nil {
|
||||
slog.Error("Server is not running.")
|
||||
return
|
||||
}
|
||||
// 关闭当前服务
|
||||
Shutdown()
|
||||
|
||||
// 重新启动服务
|
||||
Start()
|
||||
}
|
||||
|
||||
// 关闭 HTTP 服务器
|
||||
func Shutdown() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// 关闭服务器
|
||||
if err := Server.Shutdown(ctx); err != nil {
|
||||
slog.Error("Failed to shutdown server:", "error", err)
|
||||
} else {
|
||||
slog.Info("Server gracefully shutdown")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
|
||||
{
|
||||
"dbType": "mongodb",
|
||||
"mysql": {
|
||||
"host": "localhost",
|
||||
"port": "3306",
|
||||
"user": "root",
|
||||
"password": "root",
|
||||
"dbname": "godocms"
|
||||
},
|
||||
"mongodb": {
|
||||
"uri": "mongodb://localhost:27017",
|
||||
"database": "godocms"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"godocms/pkg/cache"
|
||||
"os"
|
||||
)
|
||||
|
||||
var Config Info
|
||||
var Cache cache.Cache
|
||||
|
||||
type Info struct {
|
||||
System System `json:"system"`
|
||||
Log Log `json:"log"`
|
||||
Email Email `json:"email"`
|
||||
Cache CacheConfig `json:"cache"`
|
||||
}
|
||||
type System struct {
|
||||
Debug bool `json:"debug"`
|
||||
Port int `json:"port"`
|
||||
Host string `json:"host"`
|
||||
Scheme string `json:"scheme"`
|
||||
SessionType string `json:"sessionType"`
|
||||
SessionSecret string `json:"sessionSecret"`
|
||||
|
||||
IpAccess []string `json:"ipAccess"`
|
||||
}
|
||||
type CacheConfig struct {
|
||||
Type string `json:"type"` // 缓存类型: memory/file
|
||||
FileDir string `json:"fileDir"` // 文件缓存目录(仅文件缓存需要)
|
||||
}
|
||||
type Log struct {
|
||||
WriteFile bool `json:"writeFile"`
|
||||
Path string `json:"path"`
|
||||
Filename string `json:"filename"`
|
||||
MaxSize int `json:"maxSize"`
|
||||
MaxBackups int `json:"maxBackups"`
|
||||
MaxAge int `json:"maxAge"`
|
||||
}
|
||||
type Email struct {
|
||||
From string `json:"from"`
|
||||
Host string `json:"host"`
|
||||
Password string `json:"password"`
|
||||
Username string `json:"username"`
|
||||
Port int `json:"port"`
|
||||
IsSsl bool `json:"isSsl"`
|
||||
UserLogin bool `json:"userLogin"`
|
||||
AutoRegister bool `json:"autoRegister"`
|
||||
Enable bool `json:"enable"`
|
||||
AdminLogin bool `json:"adminLogin"`
|
||||
}
|
||||
|
||||
func LoadConfig() error {
|
||||
data, err := os.ReadFile("config/system.json")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
json.Unmarshal(data, &Config)
|
||||
Cache = cache.NewCache(Config.Cache.Type, Config.Cache.FileDir)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
|
||||
{
|
||||
"dbType": "mongodb",
|
||||
"mysql": {
|
||||
"host": "localhost",
|
||||
"port": "3306",
|
||||
"user": "root",
|
||||
"password": "root",
|
||||
"dbname": "godocms"
|
||||
},
|
||||
"mongodb": {
|
||||
"uri": "mongodb://localhost:27017",
|
||||
"database": "godocms"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"gopkg.in/natefinch/lumberjack.v2"
|
||||
)
|
||||
|
||||
// InitLogger 初始化日志系统
|
||||
func InitLogger() (slog.Handler, error) {
|
||||
// 根据 Debug 字段判断是否开启文件日志记录
|
||||
handler, err := NewLogHandler(&Config.Log)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return handler, nil
|
||||
}
|
||||
|
||||
// NewLogHandler 创建一个新的日志处理器
|
||||
func NewLogHandler(log *Log) (slog.Handler, error) {
|
||||
if Config.Log.WriteFile {
|
||||
logFilePath := filepath.Join("data", log.Path, log.Filename)
|
||||
lumberjackLogger := &lumberjack.Logger{
|
||||
Filename: logFilePath,
|
||||
MaxSize: log.MaxSize,
|
||||
MaxBackups: log.MaxBackups,
|
||||
MaxAge: log.MaxAge,
|
||||
}
|
||||
|
||||
// 创建一个 slog.TextHandler,它将使用 lumberjackLogger 作为输出
|
||||
textHandler := slog.NewTextHandler(lumberjackLogger, nil)
|
||||
|
||||
return textHandler, nil
|
||||
} else {
|
||||
// 如果不是 debug 模式,使用控制台输出
|
||||
return slog.NewJSONHandler(os.Stdout, nil), nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"log": {
|
||||
"writeFile": false,
|
||||
"path": "logs",
|
||||
"filename": "access.log",
|
||||
"maxSize": 20,
|
||||
"maxBackups": 10,
|
||||
"maxAge": 7
|
||||
},
|
||||
"cache": {
|
||||
"type" : "file",
|
||||
"fileDir": "data/cache"
|
||||
},
|
||||
|
||||
"system": {
|
||||
"port": 8816,
|
||||
"ipAccess": [],
|
||||
"sessionType": "memory",
|
||||
"sessionSecret": "godocms!2981$"
|
||||
},
|
||||
"email": {
|
||||
"from": "xxx@163.com",
|
||||
"host": "smtp.163.com",
|
||||
"password": "",
|
||||
"username": "godoos",
|
||||
"port": 465,
|
||||
"isSsl": true,
|
||||
"userLogin": false,
|
||||
"autoRegister": false,
|
||||
"adminLogin": false,
|
||||
"enable": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
module godocms
|
||||
|
||||
go 1.23.8
|
||||
|
||||
require (
|
||||
github.com/btcsuite/btcutil v1.0.2
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible
|
||||
github.com/didip/tollbooth v4.0.2+incompatible
|
||||
github.com/gin-contrib/sessions v1.0.3
|
||||
github.com/gin-gonic/gin v1.10.0
|
||||
github.com/qiniu/qmgo v1.1.9
|
||||
go.mongodb.org/mongo-driver v1.17.3
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1
|
||||
gorm.io/driver/mysql v1.5.7
|
||||
gorm.io/driver/postgres v1.5.11
|
||||
gorm.io/driver/sqlite v1.5.7
|
||||
gorm.io/gorm v1.25.12
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bytedance/sonic v1.13.2 // indirect
|
||||
github.com/bytedance/sonic/loader v0.2.4 // indirect
|
||||
github.com/cloudwego/base64x v0.1.5 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
|
||||
github.com/gin-contrib/sse v1.0.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.26.0 // indirect
|
||||
github.com/go-sql-driver/mysql v1.7.0 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/golang/snappy v1.0.0 // indirect
|
||||
github.com/gorilla/context v1.1.2 // indirect
|
||||
github.com/gorilla/securecookie v1.1.2 // indirect
|
||||
github.com/gorilla/sessions v1.4.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/jackc/pgx/v5 v5.5.5 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/compress v1.18.0 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.10 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.22 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/montanaflynn/stats v0.7.1 // indirect
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
|
||||
github.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b // indirect
|
||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
github.com/wader/gormstore/v2 v2.0.3 // 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/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
|
||||
golang.org/x/arch v0.16.0 // indirect
|
||||
golang.org/x/crypto v0.37.0 // indirect
|
||||
golang.org/x/net v0.38.0 // indirect
|
||||
golang.org/x/sync v0.13.0 // indirect
|
||||
golang.org/x/sys v0.32.0 // indirect
|
||||
golang.org/x/text v0.24.0 // indirect
|
||||
golang.org/x/time v0.11.0 // indirect
|
||||
google.golang.org/protobuf v1.36.6 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
+417
@@ -0,0 +1,417 @@
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs=
|
||||
github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII=
|
||||
github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ=
|
||||
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA=
|
||||
github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg=
|
||||
github.com/btcsuite/btcutil v1.0.2 h1:9iZ1Terx9fMIOtq1VrwdqfsATL9MC2l8ZrUY6YZ2uts=
|
||||
github.com/btcsuite/btcutil v1.0.2/go.mod h1:j9HUFwoQRsZL3V4n+qG+CUnEGHOarIxfC3Le2Yhbcts=
|
||||
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg=
|
||||
github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY=
|
||||
github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc=
|
||||
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY=
|
||||
github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs=
|
||||
github.com/bytedance/sonic v1.13.2 h1:8/H1FempDZqC4VqjptGo14QQlJx8VdZJegxs6wwfqpQ=
|
||||
github.com/bytedance/sonic v1.13.2/go.mod h1:o68xyaF9u2gvVBuGHPlUVCy+ZfmNNO5ETf1+KgkJhz4=
|
||||
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
||||
github.com/bytedance/sonic/loader v0.2.4 h1:ZWCw4stuXUsn1/+zQDqeE7JKP+QO47tz7QCNan80NzY=
|
||||
github.com/bytedance/sonic/loader v0.2.4/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
|
||||
github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4=
|
||||
github.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
|
||||
github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ=
|
||||
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
|
||||
github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
|
||||
github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
|
||||
github.com/didip/tollbooth v4.0.2+incompatible h1:fVSa33JzSz0hoh2NxpwZtksAzAgd7zjmGO20HCZtF4M=
|
||||
github.com/didip/tollbooth v4.0.2+incompatible/go.mod h1:A9b0665CE6l1KmzpDws2++elm/CsuWBMa5Jv4WY0PEY=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
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/gin-contrib/sessions v1.0.3 h1:AZ4j0AalLsGqdrKNbbrKcXx9OJZqViirvNGsJTxcQps=
|
||||
github.com/gin-contrib/sessions v1.0.3/go.mod h1:5i4XMx4KPtQihnzxEqG9u1K446lO3G19jAi2GtbfsAI=
|
||||
github.com/gin-contrib/sse v1.0.0 h1:y3bT1mUWUxDpW4JLQg/HnTqV4rozuW4tC9eFKTxYI9E=
|
||||
github.com/gin-contrib/sse v1.0.0/go.mod h1:zNuFdwarAygJBht0NTKiSi3jRf6RbqeILZ9Sp6Slhe0=
|
||||
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
|
||||
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
|
||||
github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
|
||||
github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
|
||||
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
|
||||
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.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
|
||||
github.com/go-playground/validator/v10 v10.26.0 h1:SP05Nqhjcvz81uJaRfEV0YBSSSGMc/iMaVtFbr3Sw2k=
|
||||
github.com/go-playground/validator/v10 v10.26.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
|
||||
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
|
||||
github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
|
||||
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
|
||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=
|
||||
github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
|
||||
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
|
||||
github.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o=
|
||||
github.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM=
|
||||
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
|
||||
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
|
||||
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
|
||||
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
|
||||
github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=
|
||||
github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo=
|
||||
github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk=
|
||||
github.com/jackc/chunkreader/v2 v2.0.1/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk=
|
||||
github.com/jackc/pgconn v0.0.0-20190420214824-7e0022ef6ba3/go.mod h1:jkELnwuX+w9qN5YIfX0fl88Ehu4XC3keFuOJJk9pcnA=
|
||||
github.com/jackc/pgconn v0.0.0-20190824142844-760dd75542eb/go.mod h1:lLjNuW/+OfW9/pnVKPazfWOgNfH2aPem8YQ7ilXGvJE=
|
||||
github.com/jackc/pgconn v0.0.0-20190831204454-2fabfa3c18b7/go.mod h1:ZJKsE/KZfsUgOEh9hBm+xYTstcNHg7UPMVJqRfQxq4s=
|
||||
github.com/jackc/pgconn v1.8.0/go.mod h1:1C2Pb36bGIP9QHGBYCjnyhqu7Rv3sGshaQUvmfGIB/o=
|
||||
github.com/jackc/pgconn v1.9.0/go.mod h1:YctiPyvzfU11JFxoXokUOOKQXQmDMoJL9vJzHH8/2JY=
|
||||
github.com/jackc/pgconn v1.9.1-0.20210724152538-d89c8390a530/go.mod h1:4z2w8XhRbP1hYxkpTuBjTS3ne3J48K83+u0zoyvg2pI=
|
||||
github.com/jackc/pgconn v1.13.0/go.mod h1:AnowpAqO4CMIIJNZl2VJp+KrkAZciAkhEl0W0JIobpI=
|
||||
github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bYf8=
|
||||
github.com/jackc/pgmock v0.0.0-20190831213851-13a1b77aafa2/go.mod h1:fGZlG77KXmcq05nJLRkk0+p82V8B8Dw8KN2/V9c/OAE=
|
||||
github.com/jackc/pgmock v0.0.0-20201204152224-4fe30f7445fd/go.mod h1:hrBW0Enj2AZTNpt/7Y5rr2xe/9Mn757Wtb2xeBzPv2c=
|
||||
github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65/go.mod h1:5R2h2EEX+qri8jOWMbJCtaPWkrrNc7OHwsp2TCqp7ak=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgproto3 v1.1.0/go.mod h1:eR5FA3leWg7p9aeAqi37XOTgTIbkABlvcPB3E5rlc78=
|
||||
github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190420180111-c116219b62db/go.mod h1:bhq50y+xrl9n5mRYyCBFKkpRVTLYJVWeCc+mEAI3yXA=
|
||||
github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190609003834-432c2951c711/go.mod h1:uH0AWtUmuShn0bcesswc4aBTWGvw0cAxIJp+6OB//Wg=
|
||||
github.com/jackc/pgproto3/v2 v2.0.0-rc3/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM=
|
||||
github.com/jackc/pgproto3/v2 v2.0.0-rc3.0.20190831210041-4c03ce451f29/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM=
|
||||
github.com/jackc/pgproto3/v2 v2.0.6/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA=
|
||||
github.com/jackc/pgproto3/v2 v2.1.1/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA=
|
||||
github.com/jackc/pgproto3/v2 v2.3.1/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA=
|
||||
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b/go.mod h1:vsD4gTJCa9TptPL8sPkXrLZ+hDuNrZCnj29CQpr4X1E=
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgtype v0.0.0-20190421001408-4ed0de4755e0/go.mod h1:hdSHsc1V01CGwFsrv11mJRHWJ6aifDLfdV3aVjFF0zg=
|
||||
github.com/jackc/pgtype v0.0.0-20190824184912-ab885b375b90/go.mod h1:KcahbBH1nCMSo2DXpzsoWOAfFkdEtEJpPbVLq8eE+mc=
|
||||
github.com/jackc/pgtype v0.0.0-20190828014616-a8802b16cc59/go.mod h1:MWlu30kVJrUS8lot6TQqcg7mtthZ9T0EoIBFiJcmcyw=
|
||||
github.com/jackc/pgtype v1.8.1-0.20210724151600-32e20a603178/go.mod h1:C516IlIV9NKqfsMCXTdChteoXmwgUceqaLfjg2e3NlM=
|
||||
github.com/jackc/pgtype v1.12.0/go.mod h1:LUMuVrfsFfdKGLw+AFFVv6KtHOFMwRgDDzBt76IqCA4=
|
||||
github.com/jackc/pgx/v4 v4.0.0-20190420224344-cc3461e65d96/go.mod h1:mdxmSJJuR08CZQyj1PVQBHy9XOp5p8/SHH6a0psbY9Y=
|
||||
github.com/jackc/pgx/v4 v4.0.0-20190421002000-1b8f0016e912/go.mod h1:no/Y67Jkk/9WuGR0JG/JseM9irFbnEPbuWV2EELPNuM=
|
||||
github.com/jackc/pgx/v4 v4.0.0-pre1.0.20190824185557-6972a5742186/go.mod h1:X+GQnOEnf1dqHGpw7JmHqHc1NxDoalibchSk9/RWuDc=
|
||||
github.com/jackc/pgx/v4 v4.12.1-0.20210724153913-640aa07df17c/go.mod h1:1QD0+tgSXP7iUjYm9C1NxKhny7lq6ee99u/z+IHFcgs=
|
||||
github.com/jackc/pgx/v4 v4.17.2/go.mod h1:lcxIZN44yMIrWI78a5CpucdD14hX0SBDbNRvjDBItsw=
|
||||
github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw=
|
||||
github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A=
|
||||
github.com/jackc/puddle v0.0.0-20190413234325-e4ced69a3a2b/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
|
||||
github.com/jackc/puddle v0.0.0-20190608224051-11cab39313c9/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
|
||||
github.com/jackc/puddle v1.1.3/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
|
||||
github.com/jackc/puddle v1.3.0/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
|
||||
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
|
||||
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4=
|
||||
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
|
||||
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
||||
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
|
||||
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
|
||||
github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
|
||||
github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
|
||||
github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ=
|
||||
github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
|
||||
github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.15/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE=
|
||||
github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
|
||||
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
|
||||
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
|
||||
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/qiniu/qmgo v1.1.9 h1:3G3h9RLyjIUW9YSAQEPP2WqqNnboZ2Z/zO3mugjVb3E=
|
||||
github.com/qiniu/qmgo v1.1.9/go.mod h1:aba4tNSlMWrwUhe7RdILfwBRIgvBujt1y10X+T1YZSI=
|
||||
github.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b h1:aUNXCGgukb4gtY99imuIeoh8Vr0GSwAlYxPAhqZrpFc=
|
||||
github.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b/go.mod h1:wTPjTepVu7uJBYgZ0SdWHQlIas582j6cn2jgk4DDdlg=
|
||||
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ=
|
||||
github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU=
|
||||
github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc=
|
||||
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
|
||||
github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4=
|
||||
github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
|
||||
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
|
||||
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
||||
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
github.com/wader/gormstore/v2 v2.0.3 h1:/29GWPauY8xZkpLnB8hsp+dZfP3ivA9fiDw1YVNTp6U=
|
||||
github.com/wader/gormstore/v2 v2.0.3/go.mod h1:sr3N3a8F1+PBc3fHoKaphFqDXLRJ9Oe6Yow0HxKFbbg=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
|
||||
github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY=
|
||||
github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4=
|
||||
github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8=
|
||||
github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM=
|
||||
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.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q=
|
||||
go.mongodb.org/mongo-driver v1.17.1/go.mod h1:wwWm/+BuOddhcq3n68LKRmgk2wXzmF6s0SFOa0GINL4=
|
||||
go.mongodb.org/mongo-driver v1.17.3 h1:TQyXhnsWfWtgAhMtOgtYHMTkZIfBTpMTsMnd9ZBeHxQ=
|
||||
go.mongodb.org/mongo-driver v1.17.3/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ=
|
||||
go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
|
||||
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
|
||||
go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
|
||||
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
|
||||
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
|
||||
go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4=
|
||||
go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU=
|
||||
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA=
|
||||
go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
|
||||
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
|
||||
go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM=
|
||||
golang.org/x/arch v0.16.0 h1:foMtLTdyOmIniqWCHjY6+JxuC54XP1fDwx4N0ASyW+U=
|
||||
golang.org/x/arch v0.16.0/go.mod h1:JmwW7aLIoRUKgaTzhkiEFxvcEiQGyOg9BMonBJUS7EE=
|
||||
golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE=
|
||||
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200115085410-6d4e4cb37c7d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
|
||||
golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
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.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
|
||||
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
|
||||
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
|
||||
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
|
||||
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.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/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
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.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
|
||||
golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
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.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610=
|
||||
golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.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.19.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.23.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
|
||||
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
|
||||
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=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
|
||||
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||
golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk=
|
||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
golang.org/x/term v0.23.0/go.mod h1:DgV24QBUrK6jhZXl+20l6UWznPlwAHm1Q1mGHtydmSk=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
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.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
|
||||
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
|
||||
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
|
||||
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
||||
golang.org/x/tools v0.0.0-20190823170909-c4a336ef6a2f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
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/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
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-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
|
||||
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/mysql v1.4.0/go.mod h1:sSIebwZAVPiT+27jK9HIwvsqOGKx3YMPmrA3mBJR10c=
|
||||
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
|
||||
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
|
||||
gorm.io/driver/postgres v1.4.1/go.mod h1:whNfh5WhhHs96honoLjBAMwJGYEuA3m1hvgUbNXhPCw=
|
||||
gorm.io/driver/postgres v1.5.11 h1:ubBVAfbKEUld/twyKZ0IYn9rSQh448EdelLYk9Mv314=
|
||||
gorm.io/driver/postgres v1.5.11/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI=
|
||||
gorm.io/driver/sqlite v1.4.1/go.mod h1:AKZZCAoFfOWHF7Nd685Iq8Uywc0i9sWJlzpoE/INzsw=
|
||||
gorm.io/driver/sqlite v1.5.7 h1:8NvsrhP0ifM7LX9G4zPB97NwovUakUxc+2V2uuf3Z1I=
|
||||
gorm.io/driver/sqlite v1.5.7/go.mod h1:U+J8craQU6Fzkcvu8oLeAQmi50TkwPEhHDEjQZXDah4=
|
||||
gorm.io/gorm v1.23.7/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk=
|
||||
gorm.io/gorm v1.23.8/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk=
|
||||
gorm.io/gorm v1.23.10/go.mod h1:DVrVomtaYTbqs7gB/x2uVvqnXzv0nqjB396B8cG4dBA=
|
||||
gorm.io/gorm v1.24.0/go.mod h1:DVrVomtaYTbqs7gB/x2uVvqnXzv0nqjB396B8cG4dBA=
|
||||
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
||||
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
|
||||
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
|
||||
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
|
||||
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||
@@ -0,0 +1,129 @@
|
||||
package libs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"io"
|
||||
)
|
||||
|
||||
var EncryptionKey = []byte("37ac3edea15eec37b48eb1c8f769ae0c")
|
||||
|
||||
// pkcs7Pad 根据 AES 块大小对数据进行 PKCS#7 填充
|
||||
func pkcs7Pad(data []byte, blockSize int) []byte {
|
||||
padding := blockSize - len(data)%blockSize
|
||||
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
|
||||
return append(data, padtext...)
|
||||
}
|
||||
|
||||
// pkcs7Unpad 移除 PKCS#7 填充
|
||||
func pkcs7Unpad(data []byte) []byte {
|
||||
length := len(data)
|
||||
if length == 0 {
|
||||
return data
|
||||
}
|
||||
padding := int(data[length-1]) // 将 padding 转换为 int 类型
|
||||
if padding > aes.BlockSize || padding < 1 {
|
||||
return data
|
||||
}
|
||||
return data[:length-padding]
|
||||
}
|
||||
|
||||
// EncryptData 使用 AES 加密数据,并添加 HMAC-SHA256 签名
|
||||
func EncryptData(data []byte, key []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 对原始数据进行 PKCS#7 填充
|
||||
paddedData := pkcs7Pad(data, block.BlockSize())
|
||||
|
||||
// 生成随机的初始化向量
|
||||
ciphertext := make([]byte, aes.BlockSize+len(paddedData))
|
||||
iv := ciphertext[:aes.BlockSize]
|
||||
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 使用 CBC 模式加密数据
|
||||
mode := cipher.NewCBCEncrypter(block, iv)
|
||||
mode.CryptBlocks(ciphertext[aes.BlockSize:], paddedData)
|
||||
|
||||
// 计算 HMAC-SHA256 签名
|
||||
mac := hmac.New(sha256.New, key)
|
||||
mac.Write(ciphertext)
|
||||
macSum := mac.Sum(nil)
|
||||
|
||||
// 将加密后的数据和 HMAC 签名组合起来
|
||||
result := append(ciphertext, macSum...)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// DecryptData 使用 AES 解密数据,并验证 HMAC-SHA256 签名
|
||||
func DecryptData(ciphertext []byte, key []byte) ([]byte, error) {
|
||||
// 检查 HMAC-SHA256 签名
|
||||
expectedMacSize := sha256.Size
|
||||
if len(ciphertext) < expectedMacSize {
|
||||
return nil, errors.New("ciphertext too short")
|
||||
}
|
||||
|
||||
macSum := ciphertext[len(ciphertext)-expectedMacSize:]
|
||||
ciphertext = ciphertext[:len(ciphertext)-expectedMacSize]
|
||||
|
||||
// 验证 HMAC-SHA256 签名
|
||||
mac := hmac.New(sha256.New, key)
|
||||
mac.Write(ciphertext)
|
||||
calculatedMac := mac.Sum(nil)
|
||||
|
||||
if !hmac.Equal(macSum, calculatedMac) {
|
||||
return nil, errors.New("invalid MAC")
|
||||
}
|
||||
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 检查 IV 的长度
|
||||
if len(ciphertext) < aes.BlockSize {
|
||||
return nil, errors.New("ciphertext too short")
|
||||
}
|
||||
|
||||
iv := ciphertext[:aes.BlockSize]
|
||||
ciphertext = ciphertext[aes.BlockSize:]
|
||||
|
||||
// 使用 CBC 模式解密数据
|
||||
mode := cipher.NewCBCDecrypter(block, iv)
|
||||
mode.CryptBlocks(ciphertext, ciphertext)
|
||||
|
||||
// 移除 PKCS#7 填充
|
||||
unpaddedData := pkcs7Unpad(ciphertext)
|
||||
|
||||
return unpaddedData, nil
|
||||
}
|
||||
|
||||
// func main() {
|
||||
// originalData := []byte("Hello, world!")
|
||||
// key := EncryptionKey
|
||||
|
||||
// // 加密数据
|
||||
// encryptedData, err := EncryptData(originalData, key)
|
||||
// if err != nil {
|
||||
// log.Fatalf("Failed to encrypt: %v", err)
|
||||
// }
|
||||
|
||||
// // 解密数据
|
||||
// decryptedData, err := DecryptData(encryptedData, key)
|
||||
// if err != nil {
|
||||
// log.Fatalf("Failed to decrypt: %v", err)
|
||||
// }
|
||||
|
||||
// fmt.Printf("Original Data: %s\n", originalData)
|
||||
// fmt.Printf("Decrypted Data: %s\n", decryptedData)
|
||||
// }
|
||||
@@ -0,0 +1,82 @@
|
||||
package libs
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"math/rand"
|
||||
)
|
||||
|
||||
// UUID 生成指定数量的 UUID
|
||||
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
|
||||
// UUID 生成指定长度的随机字符串
|
||||
func UUID(count int) string {
|
||||
source := rand.NewSource(time.Now().UnixNano())
|
||||
random := rand.New(source)
|
||||
b := make([]byte, count)
|
||||
for i := range b {
|
||||
b[i] = letterBytes[random.Intn(len(letterBytes))]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
func Md5(src string) string {
|
||||
m := md5.New()
|
||||
m.Write([]byte(src))
|
||||
res := hex.EncodeToString(m.Sum(nil))
|
||||
return res
|
||||
}
|
||||
|
||||
func IsContain(slice []string, str string) bool {
|
||||
for _, item := range slice {
|
||||
if strings.EqualFold(item, str) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func PathExists(dir string) bool {
|
||||
_, err := os.Stat(dir)
|
||||
if err == nil {
|
||||
//log.Println("文件夹存在")
|
||||
return true
|
||||
} else if os.IsNotExist(err) {
|
||||
//log.Println("文件夹不存在")
|
||||
return false
|
||||
} else if os.IsExist(err) {
|
||||
//log.Println("文件夹存在")
|
||||
return true
|
||||
} else {
|
||||
//log.Println("发生错误:", err)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// DeleteFile 删除指定路径的文件
|
||||
// 如果文件不存在或者是文件夹,则返回错误信息
|
||||
func DeleteFile(filePath string) error {
|
||||
// 检查文件信息
|
||||
fileInfo, err := os.Stat(filePath)
|
||||
if err != nil {
|
||||
// 文件不存在
|
||||
return fmt.Errorf("文件不存在: %v", err)
|
||||
}
|
||||
|
||||
// 判断是否是文件夹
|
||||
if fileInfo.IsDir() {
|
||||
// 是文件夹
|
||||
return fmt.Errorf("指定路径是文件夹,不能删除: %v", filePath)
|
||||
}
|
||||
|
||||
// 删除文件
|
||||
err = os.Remove(filePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("删除文件失败: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package libs
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func GetIpAddress(c *gin.Context) (ipAddress string) {
|
||||
// 尝试从不同的HTTP头部获取客户端IP
|
||||
ipAddress = c.Request.Header.Get("X-Real-IP")
|
||||
if ipAddress == "" || strings.EqualFold(ipAddress, "unknown") {
|
||||
ipAddress = c.Request.Header.Get("X-Forwarded-For")
|
||||
if ipAddress != "" {
|
||||
ipAddress = strings.Split(ipAddress, ",")[0]
|
||||
} else {
|
||||
ipAddress = c.Request.Header.Get("Proxy-Client-IP")
|
||||
if ipAddress == "" {
|
||||
ipAddress = c.Request.Header.Get("WL-Proxy-Client-IP")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ipAddress == "" {
|
||||
ipAddress = c.ClientIP()
|
||||
}
|
||||
|
||||
// 检测到是本机 IP, 读取其局域网 IP 地址
|
||||
if strings.HasPrefix(ipAddress, "127.0.0.1") || strings.HasPrefix(ipAddress, "[::1]") {
|
||||
ip, err := externalIP()
|
||||
if err != nil {
|
||||
slog.Error("GetIpAddress, externalIP, err: ", "error:", err)
|
||||
}
|
||||
ipAddress = ip.String()
|
||||
}
|
||||
|
||||
return ipAddress
|
||||
}
|
||||
|
||||
// 获取非 127.0.0.1 的局域网 IP
|
||||
func externalIP() (net.IP, error) {
|
||||
ifaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, iface := range ifaces {
|
||||
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
addrs, err := iface.Addrs()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, addr := range addrs {
|
||||
var ip net.IP
|
||||
switch v := addr.(type) {
|
||||
case *net.IPNet:
|
||||
ip = v.IP
|
||||
case *net.IPAddr:
|
||||
ip = v.IP
|
||||
}
|
||||
|
||||
if ip == nil || ip.IsLoopback() {
|
||||
continue
|
||||
}
|
||||
|
||||
ip = ip.To4()
|
||||
if ip != nil {
|
||||
return ip, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil, errors.New("no non-loopback addresses available")
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package libs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/btcsuite/btcutil/base58"
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const secretKey = "godocms2!f" // 使用环境变量或配置文件管理密钥
|
||||
const expireJwtTimeHours = 8760
|
||||
const effectTime = time.Duration(expireJwtTimeHours) * time.Hour
|
||||
|
||||
// UserClaims 用于存储用户信息,以便生成令牌。
|
||||
type UserClaims struct {
|
||||
ID int64 `json:"id"`
|
||||
}
|
||||
|
||||
// TokenOutTime 返回令牌的过期时间。
|
||||
func TokenOutTime(claims *UserClaims) int64 {
|
||||
return time.Now().Add(effectTime).Unix()
|
||||
}
|
||||
|
||||
// GenerateToken 生成新的JWT令牌。
|
||||
func GenerateToken(claims *UserClaims) (string, error) {
|
||||
claimsStandard := jwt.StandardClaims{
|
||||
ExpiresAt: TokenOutTime(claims),
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"id": claims.ID,
|
||||
"exp": claimsStandard.ExpiresAt,
|
||||
})
|
||||
|
||||
signedToken, err := token.SignedString([]byte(secretKey))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("签名令牌失败: %w", err)
|
||||
}
|
||||
|
||||
base58CheckToken, err := EncodeToken(signedToken)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("编码令牌失败: %w", err)
|
||||
}
|
||||
return base58CheckToken, nil
|
||||
}
|
||||
|
||||
// ParseToken 解析和验证JWT令牌。
|
||||
func ParseToken(base58CheckTokenString string) (*UserClaims, error) {
|
||||
token, err := DecodeToken(base58CheckTokenString)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解码令牌失败: %w", err)
|
||||
}
|
||||
|
||||
parsedToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(secretKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析令牌失败: %w", err)
|
||||
}
|
||||
claims, ok := parsedToken.Claims.(jwt.MapClaims)
|
||||
if !ok || !parsedToken.Valid {
|
||||
return nil, fmt.Errorf("无效的令牌")
|
||||
}
|
||||
id, ok := claims["id"].(float64)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("无效的令牌ID")
|
||||
}
|
||||
return &UserClaims{ID: int64(id)}, nil
|
||||
}
|
||||
func Ok(ctx *gin.Context, msg string, data interface{}) {
|
||||
token := ctx.Request.Header.Get("Authorization")
|
||||
var err error
|
||||
if token != "" {
|
||||
token, err = Refresh(token)
|
||||
if err != nil {
|
||||
token = ""
|
||||
}
|
||||
}
|
||||
ctx.JSON(http.StatusOK, gin.H{
|
||||
"success": 1,
|
||||
"message": msg,
|
||||
"data": data,
|
||||
"token": token,
|
||||
"time": time.Now().Unix(),
|
||||
})
|
||||
}
|
||||
|
||||
// Refresh 刷新JWT令牌的过期时间。
|
||||
func Refresh(tokenString string) (string, error) {
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(secretKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("解析令牌失败: %w", err)
|
||||
}
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("无效的令牌")
|
||||
}
|
||||
id, ok := claims["id"].(float64)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("无效的令牌ID")
|
||||
}
|
||||
userClaims := &UserClaims{ID: int64(id)}
|
||||
claims["exp"] = time.Now().Add(effectTime).Unix()
|
||||
token.Claims = claims
|
||||
return GenerateToken(userClaims)
|
||||
}
|
||||
|
||||
// EncodeToken 压缩并编码令牌。
|
||||
func EncodeToken(token string) (string, error) {
|
||||
var b bytes.Buffer
|
||||
gz := gzip.NewWriter(&b)
|
||||
if _, err := gz.Write([]byte(token)); err != nil {
|
||||
return "", fmt.Errorf("GZIP写入错误: %w", err)
|
||||
}
|
||||
if err := gz.Close(); err != nil {
|
||||
return "", fmt.Errorf("GZIP关闭错误: %w", err)
|
||||
}
|
||||
|
||||
base64UrlSafeToken := base64.URLEncoding.EncodeToString(b.Bytes())
|
||||
return base58.CheckEncode([]byte(base64UrlSafeToken), 0x00), nil
|
||||
}
|
||||
|
||||
// DecodeToken 解码并解压令牌。
|
||||
func DecodeToken(base58CheckTokenString string) (string, error) {
|
||||
decodedData, _, err := base58.CheckDecode(base58CheckTokenString)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("Base58解码错误: %w", err)
|
||||
}
|
||||
|
||||
base64UrlSafeData, err := base64.URLEncoding.DecodeString(string(decodedData))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("Base64解码错误: %w", err)
|
||||
}
|
||||
|
||||
b := bytes.NewReader(base64UrlSafeData)
|
||||
gz, err := gzip.NewReader(b)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("GZIP读取器错误: %w", err)
|
||||
}
|
||||
defer gz.Close()
|
||||
|
||||
var b2 bytes.Buffer
|
||||
if _, err := b2.ReadFrom(gz); err != nil {
|
||||
return "", fmt.Errorf("GZIP读取错误: %w", err)
|
||||
}
|
||||
|
||||
return b2.String(), nil
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package libs
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type APIResponse struct {
|
||||
Message string `json:"message"`
|
||||
Code int `json:"code"`
|
||||
Data any `json:"data,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// 请求成功的时候 使用该方法返回信息
|
||||
func Success(ctx *gin.Context, msg string, data interface{}) {
|
||||
ctx.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"success": true,
|
||||
"message": msg,
|
||||
"data": data,
|
||||
"time": time.Now().Unix(),
|
||||
})
|
||||
}
|
||||
|
||||
// 请求失败的时候, 使用该方法返回信息
|
||||
func Error(ctx *gin.Context, msg string) {
|
||||
ctx.JSON(http.StatusOK, gin.H{
|
||||
"code": -1,
|
||||
"success": false,
|
||||
"message": msg,
|
||||
"time": time.Now().Unix(),
|
||||
})
|
||||
}
|
||||
|
||||
func ErrorMsg(ctx *gin.Context, code int, msg string, data interface{}) {
|
||||
ctx.JSON(http.StatusOK, gin.H{
|
||||
"code": code,
|
||||
"success": true,
|
||||
"message": msg,
|
||||
"data": data,
|
||||
"time": time.Now().Unix(),
|
||||
})
|
||||
}
|
||||
func ErrorLogin(ctx *gin.Context, msg string) {
|
||||
ctx.JSON(http.StatusOK, gin.H{
|
||||
"code": -2,
|
||||
"success": false,
|
||||
"message": msg,
|
||||
"time": time.Now().Unix(),
|
||||
})
|
||||
}
|
||||
func GetPage(c *gin.Context) (int, int) {
|
||||
page, _ := strconv.Atoi(c.Query("page"))
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
size, _ := strconv.Atoi(c.Query("size"))
|
||||
if size <= 0 {
|
||||
size = 10
|
||||
}
|
||||
return page, size
|
||||
}
|
||||
|
||||
type PaginatedResult struct {
|
||||
Data interface{} `json:"data"` // 当前页数据
|
||||
Page int `json:"page"` // 当前页码
|
||||
Size int `json:"size"` // 每页大小
|
||||
TotalCount int64 `json:"total_count"` // 总记录数
|
||||
TotalPages int `json:"total_pages"` // 总页数
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"godocms/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd.Start()
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func Cors() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
|
||||
origin := c.Request.Header.Get("Origin")
|
||||
if origin != "" {
|
||||
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
}
|
||||
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Length, Content-Type, Authorization, ClientID, AuthorizationAdmin,pwd")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
c.Writer.Header().Set("Access-Control-Expose-Headers", "New-Token, New-Expires-In, Content-Disposition")
|
||||
c.Writer.Header().Set("Access-Control-Max-Age", "7200")
|
||||
|
||||
if c.Request.Method == http.MethodOptions {
|
||||
c.AbortWithStatus(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"godocms/config"
|
||||
"godocms/libs"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func JwtVerify() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
url := c.Request.URL.Path
|
||||
// 检查 URL 是否以 /static/ 开头,如果是则跳过记录
|
||||
if strings.HasPrefix(url, "/static/") || strings.HasPrefix(url, "/upload/") || strings.HasPrefix(url, "/views/") || strings.HasPrefix(url, "/os/") {
|
||||
c.Next() // 继续后续处理
|
||||
return
|
||||
}
|
||||
// 根据动态路由模式获取路由信息
|
||||
routeData, ok := getRouteData(url)
|
||||
//未注册路由
|
||||
if !ok {
|
||||
log.Printf("未注册路由:%v", url)
|
||||
// log.Printf("routes:%v", config.Routes)
|
||||
libs.Error(c, "未注册路由") // 重定向到登录页面
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
if routeData.NeedAuth == 0 { // 过滤附件访问接口
|
||||
return
|
||||
}
|
||||
|
||||
token := c.GetHeader("Authorization")
|
||||
if routeData.NeedAuth == 3 {
|
||||
token = c.GetHeader("AuthorizationAdmin")
|
||||
}
|
||||
if token == "" {
|
||||
token = c.Query("token")
|
||||
}
|
||||
if token == "" {
|
||||
libs.ErrorLogin(c, "token is empty")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
// 验证 token,并存储在请求中
|
||||
user, err := libs.ParseToken(token)
|
||||
if err != nil {
|
||||
libs.ErrorLogin(c, "token is invalid")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
session := sessions.Default(c)
|
||||
|
||||
if routeData.NeedAuth == 1 {
|
||||
|
||||
clientId := c.GetHeader("ClientID")
|
||||
|
||||
if clientId == "" {
|
||||
clientId = c.Query("uuid")
|
||||
if clientId == "" {
|
||||
libs.ErrorLogin(c, "clientId is empty")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
}
|
||||
if !CheckIp(c.Request) {
|
||||
libs.Error(c, "the ip is invalid")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
userData, _ := config.Cache.GetKey("userData", clientId)
|
||||
if userData == nil {
|
||||
libs.ErrorLogin(c, "the userdata is invalid")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
m, ok := userData.(map[string]interface{})
|
||||
if !ok {
|
||||
libs.ErrorLogin(c, "invalid userData type")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
//log.Printf("userData:%v", m)
|
||||
userId, ok := m["userId"].(int32)
|
||||
if !ok {
|
||||
libs.ErrorLogin(c, "userId is not an int64")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
if userId != int32(user.ID) || userId == 0 {
|
||||
libs.ErrorLogin(c, "user is invalid")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
c.Set("userId", user.ID)
|
||||
//log.Printf("userId:%v", user.ID)
|
||||
userRoles, ok := m["userRoles"].(string)
|
||||
if !ok {
|
||||
libs.Error(c, "user roles is invalid")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
hasAuth := checkRoles(userRoles, url)
|
||||
if !hasAuth {
|
||||
libs.Error(c, "user roles check invalid")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
}
|
||||
if routeData.NeedAuth == 2 {
|
||||
memberId := session.Get("memberId")
|
||||
if memberId == nil {
|
||||
libs.ErrorLogin(c, "member is invalid")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
|
||||
uid := getUserId(memberId)
|
||||
log.Printf("memberId:%v,uid:%v,user.ID:%v", memberId, uid, user.ID)
|
||||
if uid != user.ID || uid == 0 {
|
||||
log.Printf("member is invalid")
|
||||
libs.ErrorLogin(c, "member is invalid")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
c.Set("memberId", uid)
|
||||
if uid > 1 {
|
||||
memberRoles := session.Get("memberRoles")
|
||||
log.Printf("memberRoles:%v", memberRoles)
|
||||
if memberRoles == nil {
|
||||
libs.Error(c, "member roles is invalid")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
memberRole := memberRoles.(string) + ",/index,/member/loginout,/member/welcome,/member/userinfo"
|
||||
//log.Printf("adminRules:%v", adminRules)
|
||||
hasAuth := checkRoles(memberRole, url)
|
||||
if !hasAuth {
|
||||
libs.Error(c, "admin roles is invalid")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if routeData.NeedAuth == 3 {
|
||||
adminId := session.Get("adminId")
|
||||
if adminId == nil {
|
||||
libs.ErrorLogin(c, "admin is invalid")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
|
||||
uid := getUserId(adminId)
|
||||
log.Printf("adminId:%v,uid:%v,user.ID:%v", adminId, uid, user.ID)
|
||||
if uid != user.ID || uid == 0 {
|
||||
log.Printf("admin is invalid")
|
||||
libs.ErrorLogin(c, "admin is invalid")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
c.Set("adminId", uid)
|
||||
if uid > 1 {
|
||||
adminRoles := session.Get("adminRoles")
|
||||
log.Printf("adminRoles:%v", adminRoles)
|
||||
if adminRoles == nil {
|
||||
libs.Error(c, "admin roles is invalid")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
adminRules := adminRoles.(string) + ",/index,/admin/loginout,/admin/welcome,/admin/userinfo"
|
||||
//log.Printf("adminRules:%v", adminRules)
|
||||
hasAuth := checkRoles(adminRules, url)
|
||||
if !hasAuth {
|
||||
libs.Error(c, "admin roles is invalid")
|
||||
c.Abort() // 终止后续处理
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
func getRouteData(url string) (Route, bool) {
|
||||
for path, route := range Routes {
|
||||
// 检查 URL 是否匹配动态路由
|
||||
if matchPath(url, path) {
|
||||
return route, true
|
||||
}
|
||||
}
|
||||
return Route{}, false
|
||||
}
|
||||
|
||||
// matchPath 检查 URL 是否匹配给定的路径模式
|
||||
func matchPath(url, pattern string) bool {
|
||||
parts := strings.Split(pattern, "/")
|
||||
urlParts := strings.Split(url, "/")
|
||||
|
||||
if len(parts) != len(urlParts) {
|
||||
return false
|
||||
}
|
||||
//log.Printf("url:%v,pattern:%v", url, pattern)
|
||||
if strings.Contains(pattern, ":") {
|
||||
for i, part := range parts {
|
||||
if part == "" { // 空字符串处理
|
||||
continue
|
||||
}
|
||||
if part[0] == ':' { // 动态参数
|
||||
paramName := part[1:]
|
||||
if strings.Contains(paramName, "id") { // 数字参数
|
||||
if _, err := strconv.Atoi(urlParts[i]); err != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
} else if part != urlParts[i] { // 静态部分
|
||||
return false
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if pattern != url {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
func getUserId(userId interface{}) int64 {
|
||||
var userIdInt64 int64
|
||||
switch v := userId.(type) {
|
||||
case int32:
|
||||
userIdInt64 = int64(v)
|
||||
case int64:
|
||||
userIdInt64 = int64(v)
|
||||
default: // 终止后续处理
|
||||
userIdInt64 = 0
|
||||
}
|
||||
return userIdInt64
|
||||
}
|
||||
func checkRoles(rules string, url string) bool {
|
||||
if rules == "*" || rules == "-1" {
|
||||
return true
|
||||
}
|
||||
if rules == "" {
|
||||
return false
|
||||
}
|
||||
userRoleArray := strings.Split(rules, ",")
|
||||
hasAuth := false
|
||||
for _, path := range userRoleArray {
|
||||
if matchPath(url, path) {
|
||||
hasAuth = true
|
||||
break
|
||||
}
|
||||
}
|
||||
return hasAuth
|
||||
}
|
||||
|
||||
// CheckIp 验证客户端 IP 是否允许访问
|
||||
func CheckIp(r *http.Request) bool {
|
||||
if strings.HasPrefix(r.URL.Scheme, "wails") {
|
||||
return true
|
||||
}
|
||||
|
||||
clientIP := r.RemoteAddr
|
||||
host := r.Host
|
||||
ip, _, err := net.SplitHostPort(clientIP)
|
||||
if err != nil {
|
||||
//fmt.Printf("Error splitting host and port: %v\n", err)
|
||||
return false
|
||||
}
|
||||
|
||||
// 解析 IP 地址
|
||||
ipAddress := net.ParseIP(ip)
|
||||
//fmt.Printf("clientIP:%v, host:%v\n", clientIP, host)
|
||||
|
||||
// 允许本机访问
|
||||
if ipAddress.IsLoopback() || host == "localhost" {
|
||||
return true
|
||||
}
|
||||
|
||||
// 获取允许的 IP 和域名列表
|
||||
ipAndDomainList := config.Config.System.IpAccess
|
||||
//fmt.Printf("ipAndDomainList:%v\n", ipAndDomainList)
|
||||
if len(ipAndDomainList) == 0 {
|
||||
return true
|
||||
}
|
||||
// 检查 IP 地址
|
||||
for _, allowed := range ipAndDomainList {
|
||||
if ipAddress.String() == allowed {
|
||||
return true
|
||||
}
|
||||
// 检查域名
|
||||
if host == allowed {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/didip/tollbooth"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func LimitHandler() gin.HandlerFunc {
|
||||
lmt := tollbooth.NewLimiter(100, nil)
|
||||
lmt.SetMessage("您访问过于频繁,系统安全检查认为恶意攻击。")
|
||||
return func(c *gin.Context) {
|
||||
httpError := tollbooth.LimitByRequest(lmt, c.Writer, c.Request)
|
||||
if httpError != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 1,
|
||||
"message": "您的操作太频繁,请稍后再试!",
|
||||
"result": nil,
|
||||
})
|
||||
c.Data(httpError.StatusCode, lmt.GetMessageContentType(), []byte(httpError.Message))
|
||||
c.Abort()
|
||||
} else {
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"godocms/config"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// LoggerMiddleware 是一个简单的日志中间件
|
||||
func LoggerMiddleware(handler slog.Handler) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// 获取请求的 Host
|
||||
host := c.Request.Host
|
||||
// 获取请求的 Scheme
|
||||
scheme := "http"
|
||||
if c.Request.TLS != nil {
|
||||
scheme = "https"
|
||||
}
|
||||
config.Config.System.Host = host
|
||||
config.Config.System.Scheme = scheme
|
||||
url := c.Request.URL.Path
|
||||
// 检查 URL 是否以 /static/ 开头,如果是则跳过记录
|
||||
if strings.HasPrefix(url, "/static/") || strings.HasPrefix(url, "/upload/") {
|
||||
c.Next() // 继续后续处理
|
||||
return
|
||||
}
|
||||
startTime := time.Now()
|
||||
c.Next() // 执行后续的处理函数
|
||||
logger := slog.New(handler)
|
||||
// 记录请求的信息
|
||||
logger.Info("Request completed",
|
||||
slog.String("method", c.Request.Method),
|
||||
slog.String("path", url),
|
||||
slog.Any("status", c.Writer.Status()),
|
||||
slog.Duration("duration", time.Since(startTime)),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"godocms/config"
|
||||
"godocms/libs"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// UserActivity 结构体用于存储用户的单个活动数据
|
||||
type UserActivity struct {
|
||||
Duration int64 `json:"duration"` // 修改为 int64 类型
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
}
|
||||
|
||||
// UserActivities 结构体用于存储用户的多个活动数据
|
||||
type UserActivities map[string]UserActivity
|
||||
|
||||
// UserStatus 结构体用于存储每个 IP 地址的状态和活动数据
|
||||
type UserStatus struct {
|
||||
Activities UserActivities `json:"activities"`
|
||||
LastSeen time.Time `json:"last_seen"`
|
||||
}
|
||||
|
||||
// UserStatuses 映射表用于存储每个 IP 地址的状态和活动数据
|
||||
var (
|
||||
UserStatusesMutex sync.Mutex
|
||||
UserStatuses sync.Map
|
||||
)
|
||||
var ifWrite = false
|
||||
|
||||
// func init() {
|
||||
// InitOnlineFile()
|
||||
// }
|
||||
|
||||
// recordUserActivity 中间件记录用户的 IP 地址、请求的 URL 和开始时间
|
||||
func RecordUserActivity() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
url := c.Request.URL.Path // 获取请求的 URL
|
||||
if strings.HasPrefix(url, "/static/") || strings.HasPrefix(url, "/upload/") {
|
||||
c.Next() // 继续后续处理
|
||||
return
|
||||
}
|
||||
ip := libs.GetIpAddress(c) // 获取客户端 IP 地址
|
||||
currentTime := time.Now()
|
||||
//log.Printf("IP:%s,URL:%s,Time:%s", ip, url, currentTime)
|
||||
// 检查 URL 是否以 /static/ 开头,如果是则跳过记录
|
||||
|
||||
// 更新用户的活动数据
|
||||
UserStatusesMutex.Lock()
|
||||
userStatus, ok := UserStatuses.Load(ip)
|
||||
if ok {
|
||||
// 如果用户已经存在,则更新其停留时长
|
||||
status := userStatus.(UserStatus)
|
||||
if activity, exists := status.Activities[url]; exists {
|
||||
durationInSeconds := int64(currentTime.Sub(activity.Timestamp).Seconds()) // 转换为秒
|
||||
activity.Duration += durationInSeconds
|
||||
activity.Timestamp = currentTime
|
||||
status.Activities[url] = activity
|
||||
} else {
|
||||
status.Activities[url] = UserActivity{
|
||||
Timestamp: currentTime,
|
||||
Duration: 0,
|
||||
}
|
||||
}
|
||||
status.LastSeen = currentTime
|
||||
userStatus = status
|
||||
} else {
|
||||
// 如果用户不存在,则创建新的状态记录
|
||||
userStatus = UserStatus{
|
||||
Activities: UserActivities{
|
||||
url: UserActivity{
|
||||
Timestamp: currentTime,
|
||||
Duration: 0,
|
||||
},
|
||||
},
|
||||
LastSeen: currentTime,
|
||||
}
|
||||
}
|
||||
|
||||
// 将用户状态数据保存回映射表
|
||||
UserStatuses.Store(ip, userStatus)
|
||||
ifWrite = true
|
||||
UserStatusesMutex.Unlock()
|
||||
c.Next() // 继续后续处理
|
||||
}
|
||||
}
|
||||
|
||||
// 读取 JSON 文件
|
||||
func InitOnlineFile() error {
|
||||
logPath := getLogPath()
|
||||
//log.Printf("logpath is:%s", logPath)
|
||||
data, err := os.ReadFile(logPath)
|
||||
if os.IsNotExist(err) {
|
||||
return nil // 文件不存在,不需要做任何事情
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 创建临时映射表用于反序列化
|
||||
var mapped map[string]UserStatus
|
||||
if err := json.Unmarshal(data, &mapped); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 清空 UserStatuses 映射表
|
||||
UserStatusesMutex.Lock()
|
||||
UserStatuses = sync.Map{}
|
||||
UserStatusesMutex.Unlock()
|
||||
|
||||
// 将数据加载到 UserStatuses 映射表中
|
||||
for k, v := range mapped {
|
||||
UserStatuses.Store(k, v)
|
||||
}
|
||||
StartTicker()
|
||||
return nil
|
||||
}
|
||||
|
||||
// 启动定时器
|
||||
func StartTicker() {
|
||||
ticker := time.NewTicker(1 * time.Minute) // 每分钟检查一次
|
||||
go func() {
|
||||
for range ticker.C {
|
||||
if ifWrite {
|
||||
if err := WriteJSONFile(); err != nil {
|
||||
fmt.Println("Error writing to file:", err)
|
||||
}
|
||||
ifWrite = false
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// 获取日志文件目录
|
||||
func getLogPath() string {
|
||||
filename := fmt.Sprintf("online_%s.json", time.Now().Format("2006-01-02"))
|
||||
// 获取程序执行文件所在目录的绝对路径
|
||||
exePath, err := os.Executable()
|
||||
if err != nil {
|
||||
return filename
|
||||
}
|
||||
exeDir := filepath.Dir(exePath)
|
||||
|
||||
// 构建 logs 文件夹的绝对路径
|
||||
logDir := filepath.Join(exeDir, "logs")
|
||||
if !libs.PathExists(logDir) {
|
||||
os.Mkdir(logDir, 0755)
|
||||
}
|
||||
|
||||
return filepath.Join(logDir, filename)
|
||||
}
|
||||
|
||||
// 写入 JSON 文件
|
||||
func WriteJSONFile() error {
|
||||
// 将 sync.Map 转换为普通的映射表
|
||||
mapped := make(map[string]UserStatus)
|
||||
UserStatuses.Range(func(key, value interface{}) bool {
|
||||
mapped[key.(string)] = value.(UserStatus)
|
||||
return true
|
||||
})
|
||||
|
||||
data, err := json.MarshalIndent(mapped, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 将文件写入 logs 目录
|
||||
logPath := getLogPath()
|
||||
return os.WriteFile(logPath, data, 0644)
|
||||
}
|
||||
|
||||
func UserAccessRecord() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
uid := c.GetInt64("userId")
|
||||
if uid == 0 {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
UserStatusesMutex.Lock()
|
||||
// 获取缓存的数据
|
||||
var origin map[int64]int64
|
||||
var ok bool
|
||||
data, _ := config.Cache.Get("user_online")
|
||||
if data == nil {
|
||||
origin = make(map[int64]int64)
|
||||
} else {
|
||||
if origin, ok = data.(map[int64]int64); !ok {
|
||||
origin = make(map[int64]int64)
|
||||
}
|
||||
}
|
||||
|
||||
origin[uid] = time.Now().Unix()
|
||||
config.Cache.Set("user_online", origin, 60*24)
|
||||
UserStatusesMutex.Unlock()
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// 启动定时心跳检查任务
|
||||
func StartHeartbeatCheckOnline() {
|
||||
ticker := time.NewTicker(3 * time.Minute) // 每 3 分钟执行一次
|
||||
defer ticker.Stop()
|
||||
|
||||
for range ticker.C {
|
||||
// 每次心跳检查,检查不活跃的用户
|
||||
checkInactiveUsers()
|
||||
}
|
||||
}
|
||||
|
||||
// 检查不在线的用户
|
||||
func checkInactiveUsers() {
|
||||
UserStatusesMutex.Lock() // 锁定对缓存的访问
|
||||
defer UserStatusesMutex.Unlock()
|
||||
|
||||
now := time.Now().Unix()
|
||||
// 获取缓存的数据
|
||||
var origin map[int64]int64
|
||||
var ok bool
|
||||
data, _ := config.Cache.Get("user_online")
|
||||
if data == nil {
|
||||
log.Println("No user activity data found in cache.")
|
||||
return
|
||||
}
|
||||
|
||||
// 安全地进行类型断言
|
||||
if origin, ok = data.(map[int64]int64); !ok {
|
||||
log.Println("Cache data is not of the expected type.")
|
||||
return
|
||||
}
|
||||
|
||||
// 遍历所有用户的活动记录,检查是否有不在线的用户
|
||||
for uid, lastActivityTime := range origin {
|
||||
if now-lastActivityTime > 30*60 { // 如果用户的最后活动时间超过 30 分钟, 视为不在线
|
||||
delete(origin, uid)
|
||||
}
|
||||
}
|
||||
|
||||
config.Cache.Set("user_online", origin, 60*24)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Route 结构体用于存储路由信息
|
||||
type Route struct {
|
||||
Method string `json:"method"`
|
||||
Path string `json:"path"`
|
||||
Name string `json:"name"`
|
||||
Handler gin.HandlerFunc `json:"-"`
|
||||
// 添加一个字段表示是否需要权限校验
|
||||
NeedAuth int `json:"needAuth"`
|
||||
}
|
||||
|
||||
// routes 存储所有需要注册的路由
|
||||
var Routes = make(map[string]Route)
|
||||
|
||||
// RegisterRouter 注册控制器中的路由
|
||||
func RegisterRouter(method string, path string, handler gin.HandlerFunc, needAuth int, name string) {
|
||||
path = strings.TrimPrefix(path, "/")
|
||||
path = strings.TrimSuffix(path, "/")
|
||||
|
||||
// 拼接路由地址
|
||||
if path == "index" {
|
||||
path = "/"
|
||||
} else {
|
||||
path = "/" + strings.ToLower(path)
|
||||
}
|
||||
|
||||
// 构造键值
|
||||
//key := method + ":" + path
|
||||
|
||||
// 添加路由
|
||||
Routes[path] = Route{
|
||||
Path: path,
|
||||
Method: method,
|
||||
Handler: handler,
|
||||
NeedAuth: needAuth,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
//slog.Info("Register route", "method", method, "path", path)
|
||||
}
|
||||
|
||||
// BindRouter 绑定所有注册的路由到 Gin 引擎
|
||||
func BindRouter(e *gin.Engine) {
|
||||
for _, route := range Routes {
|
||||
switch route.Method {
|
||||
case "GET":
|
||||
e.GET(route.Path, route.Handler)
|
||||
case "POST":
|
||||
e.POST(route.Path, route.Handler)
|
||||
case "DELETE":
|
||||
e.DELETE(route.Path, route.Handler)
|
||||
case "PUT":
|
||||
e.PUT(route.Path, route.Handler)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// HandleNotFound 自定义 404 处理器
|
||||
func HandleNotFound(c *gin.Context) {
|
||||
// 重定向到自定义的 404 页面
|
||||
c.Redirect(302, "/home/notfond/")
|
||||
}
|
||||
|
||||
// Recover 自定义 panic 处理器
|
||||
func Recover(c *gin.Context) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
// 打印错误堆栈信息
|
||||
log.Printf("panic: %v\n", r)
|
||||
}
|
||||
}()
|
||||
|
||||
// 加载完 defer recover,继续后续接口调用
|
||||
c.Next()
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"godocms/config"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-contrib/sessions/cookie"
|
||||
gormsessions "github.com/gin-contrib/sessions/gorm"
|
||||
"github.com/gin-contrib/sessions/memstore"
|
||||
)
|
||||
|
||||
func GetSessionStore() gormsessions.Store {
|
||||
|
||||
if config.Config.System.SessionType == "cookie" {
|
||||
// 创建一个 cookie store
|
||||
store := cookie.NewStore([]byte(config.Config.System.SessionSecret))
|
||||
|
||||
// 配置 cookie,使用 github.com/gin-contrib/sessions.Options 类型
|
||||
store.Options(sessions.Options{
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: false, // 如果使用 HTTPS
|
||||
SameSite: http.SameSiteNoneMode,
|
||||
MaxAge: int(24 * time.Hour / time.Second), // MaxAge 单位为秒
|
||||
})
|
||||
|
||||
return store
|
||||
} else {
|
||||
return memstore.NewStore([]byte(config.Config.System.SessionSecret))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// 统一用户模型
|
||||
type User struct {
|
||||
ID interface{} `json:"id" gorm:"primaryKey" bson:"_id,omitempty"`
|
||||
Name string `json:"name" gorm:"size:100" bson:"name"`
|
||||
Email string `json:"email" gorm:"size:100;uniqueIndex" bson:"email"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime" bson:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime" bson:"updated_at"`
|
||||
}
|
||||
Vendored
+65
@@ -0,0 +1,65 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 初始化缓存
|
||||
// cache, err := cache.NewCache(cache.CacheConfig{
|
||||
// Type: cache.FileCacheType,
|
||||
// FileDir: "data/cache",
|
||||
// })
|
||||
// if err != nil {
|
||||
// log.Fatal(err)
|
||||
// }
|
||||
|
||||
// // 设置缓存(有效期10分钟)
|
||||
// err = cache.Set("user:1", userData, 10*time.Minute)
|
||||
|
||||
// // 获取缓存
|
||||
// val, err := cache.Get("user:1")
|
||||
|
||||
// // 删除缓存
|
||||
// err = cache.Delete("user:1")
|
||||
|
||||
// CacheItem 缓存项结构
|
||||
type CacheItem struct {
|
||||
Value interface{} `json:"value"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
}
|
||||
|
||||
// Cache 定义缓存接口
|
||||
type Cache interface {
|
||||
// Set 设置缓存
|
||||
Set(key string, value interface{}, ttl time.Duration) error
|
||||
// Get 获取缓存
|
||||
Get(key string) (interface{}, error)
|
||||
GetKey(key string, val string) (interface{}, error)
|
||||
// Delete 删除缓存
|
||||
Delete(key string) error
|
||||
// Clear 清空缓存
|
||||
Clear() error
|
||||
// Exists 检查缓存是否存在
|
||||
Exists(key string) (bool, error)
|
||||
}
|
||||
|
||||
var (
|
||||
ErrCacheMiss = errors.New("cache: key not found")
|
||||
ErrCacheExpired = errors.New("cache: key expired")
|
||||
)
|
||||
|
||||
// NewCache 创建缓存实例
|
||||
func NewCache(cacheType string, fileDir string) Cache {
|
||||
switch cacheType {
|
||||
case "memory":
|
||||
return NewMemoryCache()
|
||||
case "file":
|
||||
if fileDir == "" {
|
||||
return NewMemoryCache()
|
||||
}
|
||||
return NewFileCache(fileDir)
|
||||
default:
|
||||
return NewMemoryCache()
|
||||
}
|
||||
}
|
||||
Vendored
+124
@@ -0,0 +1,124 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// fileCache 文件缓存实现
|
||||
type fileCache struct {
|
||||
mu sync.RWMutex
|
||||
dir string
|
||||
}
|
||||
|
||||
// NewFileCache 创建文件缓存实例
|
||||
func NewFileCache(dir string) *fileCache {
|
||||
return &fileCache{
|
||||
dir: dir,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *fileCache) Set(key string, value interface{}, ttl time.Duration) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
// 确保目录存在
|
||||
if err := os.MkdirAll(c.dir, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 准备缓存数据
|
||||
item := CacheItem{
|
||||
Value: value,
|
||||
ExpiresAt: time.Now().Add(ttl),
|
||||
}
|
||||
|
||||
data, err := json.Marshal(item)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 写入文件
|
||||
filePath := filepath.Join(c.dir, key)
|
||||
return os.WriteFile(filePath, data, 0644)
|
||||
}
|
||||
|
||||
func (c *fileCache) Get(key string) (interface{}, error) {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
|
||||
filePath := filepath.Join(c.dir, key)
|
||||
data, err := os.ReadFile(filePath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, ErrCacheMiss
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var item CacheItem
|
||||
if err := json.Unmarshal(data, &item); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if item.ExpiresAt.Before(time.Now()) {
|
||||
_ = os.Remove(filePath) // 清理过期缓存
|
||||
return nil, ErrCacheExpired
|
||||
}
|
||||
|
||||
return item.Value, nil
|
||||
}
|
||||
func (c *fileCache) GetKey(key string, clientId string) (interface{}, error) {
|
||||
return c.Get(key + ":" + clientId)
|
||||
}
|
||||
func (c *fileCache) Delete(key string) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
filePath := filepath.Join(c.dir, key)
|
||||
if _, err := os.Stat(filePath); os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return os.Remove(filePath)
|
||||
}
|
||||
|
||||
func (c *fileCache) Clear() error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
entries, err := os.ReadDir(c.dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
_ = os.Remove(filepath.Join(c.dir, entry.Name()))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *fileCache) Exists(key string) (bool, error) {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
|
||||
filePath := filepath.Join(c.dir, key)
|
||||
if _, err := os.Stat(filePath); os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// 检查是否过期
|
||||
val, err := c.Get(key)
|
||||
if err == ErrCacheExpired {
|
||||
return false, nil
|
||||
}
|
||||
return val != nil, err
|
||||
}
|
||||
|
||||
// PathExists 检查路径是否存在
|
||||
func PathExists(path string) bool {
|
||||
_, err := os.Stat(path)
|
||||
return !os.IsNotExist(err)
|
||||
}
|
||||
Vendored
+85
@@ -0,0 +1,85 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// memoryCache 内存缓存实现
|
||||
type memoryCache struct {
|
||||
mu sync.RWMutex
|
||||
data map[string]CacheItem
|
||||
}
|
||||
|
||||
// NewMemoryCache 创建内存缓存实例
|
||||
func NewMemoryCache() *memoryCache {
|
||||
return &memoryCache{
|
||||
data: make(map[string]CacheItem),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *memoryCache) Set(key string, value interface{}, ttl time.Duration) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
expiresAt := time.Now().Add(ttl)
|
||||
c.data[key] = CacheItem{
|
||||
Value: value,
|
||||
ExpiresAt: expiresAt,
|
||||
}
|
||||
|
||||
// 设置过期清理
|
||||
time.AfterFunc(ttl, func() {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if item, ok := c.data[key]; ok && item.ExpiresAt.Before(time.Now()) {
|
||||
delete(c.data, key)
|
||||
}
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *memoryCache) Get(key string) (interface{}, error) {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
|
||||
item, ok := c.data[key]
|
||||
if !ok {
|
||||
return nil, ErrCacheMiss
|
||||
}
|
||||
if item.ExpiresAt.Before(time.Now()) {
|
||||
return nil, ErrCacheExpired
|
||||
}
|
||||
return item.Value, nil
|
||||
}
|
||||
func (c *memoryCache) GetKey(key string, clientId string) (interface{}, error) {
|
||||
return c.Get(key + ":" + clientId)
|
||||
}
|
||||
func (c *memoryCache) Delete(key string) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
delete(c.data, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *memoryCache) Clear() error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.data = make(map[string]CacheItem)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *memoryCache) Exists(key string) (bool, error) {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
|
||||
item, ok := c.data[key]
|
||||
if !ok {
|
||||
return false, nil
|
||||
}
|
||||
if item.ExpiresAt.Before(time.Now()) {
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package dbfactory
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"godocms/libs"
|
||||
"math"
|
||||
"reflect"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// BaseController 是一个通用的控制器基类
|
||||
type BaseController struct{}
|
||||
|
||||
// GetPagination 获取分页参数
|
||||
func (b *BaseController) GetPagination(ctx *gin.Context) (int, int) {
|
||||
pageSize := validateParameter(ctx.DefaultQuery("limit", "10"), 10, 1, 100)
|
||||
page := validateParameter(ctx.Query("page"), 1, 1, math.MaxInt32)
|
||||
return page, pageSize
|
||||
}
|
||||
|
||||
// validateParameter 解析并校验参数,确保其在指定范围内
|
||||
func validateParameter(param string, defaultValue, min, max int) int {
|
||||
value, err := strconv.Atoi(param)
|
||||
if err != nil || value < min || value > max {
|
||||
return defaultValue
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// List 获取列表
|
||||
func (b *BaseController) List(ctx *gin.Context, table string, conditions map[string]interface{}, orderby string, result *PageResult) {
|
||||
page, pageSize := b.GetPagination(ctx)
|
||||
|
||||
var list *PageResult
|
||||
pageParam := PageParams{Page: page, PageSize: pageSize, OrderBy: orderby}
|
||||
err := Db.GetPage(table, conditions, pageParam, list)
|
||||
if err != nil {
|
||||
libs.Error(ctx, "获取"+table+"列表失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
libs.Success(ctx, "获取"+table+"列表成功", list)
|
||||
}
|
||||
|
||||
// AddBefore 添加前的页面展示
|
||||
func (b *BaseController) AddBefore(ctx *gin.Context) {
|
||||
libs.Success(ctx, "success", nil)
|
||||
}
|
||||
|
||||
// AddSave 添加记录
|
||||
func (b *BaseController) AddSave(ctx *gin.Context, model interface{}, tableName string) {
|
||||
if err := ctx.ShouldBindJSON(model); err != nil {
|
||||
libs.Error(ctx, "参数错误: "+err.Error())
|
||||
return
|
||||
}
|
||||
res := Db.Create(tableName, model)
|
||||
if res != nil {
|
||||
libs.Error(ctx, "添加"+tableName+"失败: "+res.Error())
|
||||
return
|
||||
}
|
||||
libs.Success(ctx, "添加成功", nil)
|
||||
}
|
||||
|
||||
// EditBefore 编辑前的页面展示
|
||||
func (b *BaseController) EditBefore(ctx *gin.Context, model interface{}, tableName string) {
|
||||
idStr := ctx.Query("id")
|
||||
if idStr == "" {
|
||||
libs.Error(ctx, "id为空")
|
||||
return
|
||||
}
|
||||
id, err := strconv.Atoi(idStr)
|
||||
if err != nil {
|
||||
libs.Error(ctx, "参数不是数字")
|
||||
return
|
||||
}
|
||||
if err := Db.GetByID(tableName, id, model).Error; err != nil {
|
||||
libs.Error(ctx, "获取"+tableName+"失败:"+err())
|
||||
return
|
||||
}
|
||||
libs.Success(ctx, "获取"+tableName+"成功", model)
|
||||
}
|
||||
|
||||
// EditSave 编辑记录
|
||||
func (b *BaseController) EditSave(ctx *gin.Context, model interface{}, tableName string) {
|
||||
if err := ctx.ShouldBindJSON(model); err != nil {
|
||||
libs.Error(ctx, "参数错误: "+err.Error())
|
||||
return
|
||||
}
|
||||
if err := Db.Update(tableName, model).Error; err != nil {
|
||||
libs.Error(ctx, "编辑"+tableName+"失败: "+err())
|
||||
return
|
||||
}
|
||||
libs.Success(ctx, "编辑成功", nil)
|
||||
}
|
||||
|
||||
// Delete 删除记录
|
||||
func (b *BaseController) Delete(ctx *gin.Context, model interface{}, tableName string) {
|
||||
idStr := ctx.Query("id")
|
||||
if idStr == "" {
|
||||
libs.Error(ctx, "id为空")
|
||||
return
|
||||
}
|
||||
id, err := strconv.Atoi(idStr)
|
||||
if err != nil {
|
||||
libs.Error(ctx, "参数不是数字")
|
||||
return
|
||||
}
|
||||
if err := Db.Delete(tableName, id).Error; err != nil {
|
||||
libs.Error(ctx, "删除"+tableName+"失败: "+err())
|
||||
return
|
||||
}
|
||||
libs.Success(ctx, "删除成功", nil)
|
||||
}
|
||||
func (b *BaseController) GetQueryInt(ctx *gin.Context, param string) (int, error) {
|
||||
idStr := ctx.Query(param)
|
||||
if idStr == "" {
|
||||
return 0, fmt.Errorf("id为空")
|
||||
}
|
||||
id, err := strconv.Atoi(idStr)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("参数不是数字")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// UpdateEnable 更新 enable 字段
|
||||
func (b *BaseController) UpdateEnable(ctx *gin.Context, model interface{}, tableName string) {
|
||||
id, err := b.GetQueryInt(ctx, "id")
|
||||
if err != nil {
|
||||
libs.Error(ctx, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
db := Db
|
||||
if err := db.GetByID(tableName, id, model).Error; err != nil {
|
||||
libs.Error(ctx, "获取"+tableName+"失败: "+err())
|
||||
return
|
||||
}
|
||||
|
||||
// 使用反射获取 enable 字段的值
|
||||
v := reflect.ValueOf(model).Elem()
|
||||
enableField := v.FieldByName("Enable")
|
||||
if !enableField.IsValid() {
|
||||
libs.Error(ctx, "模型中没有 enable 字段")
|
||||
return
|
||||
}
|
||||
|
||||
// 检查 enable 字段是否可设置
|
||||
if !enableField.CanSet() {
|
||||
libs.Error(ctx, "enable 字段不可设置")
|
||||
return
|
||||
}
|
||||
|
||||
// 设置 enable 字段的值
|
||||
enable := !enableField.Bool()
|
||||
enableField.SetBool(enable)
|
||||
|
||||
if err := db.Update(tableName, model).Error; err != nil {
|
||||
libs.Error(ctx, "更新"+tableName+"的enable字段失败: "+err())
|
||||
return
|
||||
}
|
||||
|
||||
libs.Success(ctx, "更新成功", nil)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package dbfactory
|
||||
|
||||
import "context"
|
||||
|
||||
// 事务隔离级别
|
||||
type IsolationLevel int
|
||||
|
||||
const (
|
||||
LevelDefault IsolationLevel = iota
|
||||
LevelReadUncommitted
|
||||
LevelReadCommitted
|
||||
LevelRepeatableRead
|
||||
LevelSerializable
|
||||
)
|
||||
|
||||
// 事务选项
|
||||
type TxOptions struct {
|
||||
Isolation IsolationLevel
|
||||
ReadOnly bool
|
||||
}
|
||||
|
||||
// 分页参数
|
||||
type PageParams struct {
|
||||
Page int
|
||||
PageSize int
|
||||
OrderBy string
|
||||
}
|
||||
|
||||
// 分页结果
|
||||
type PageResult struct {
|
||||
Total int64
|
||||
Data interface{}
|
||||
}
|
||||
|
||||
// 基础CRUD接口
|
||||
type BaseRepository interface {
|
||||
// 单条操作
|
||||
Create(table string, entity interface{}) error
|
||||
Count(table string, conditions map[string]interface{}) (int64, error)
|
||||
GetByID(table string, id interface{}, result interface{}) error
|
||||
Update(table string, entity interface{}) error
|
||||
Delete(table string, id interface{}) error
|
||||
AutoMigrate(models ...interface{}) error
|
||||
// 查询操作
|
||||
GetOne(table string, conditions map[string]interface{}, result interface{}) error
|
||||
GetList(table string, conditions map[string]interface{}, result interface{}) error
|
||||
GetPage(table string, conditions map[string]interface{}, pageParams PageParams, result *PageResult) error
|
||||
|
||||
// 批量操作
|
||||
BatchCreate(table string, entities []interface{}) error
|
||||
BatchDelete(table string, ids []interface{}) error
|
||||
|
||||
// 联表查询
|
||||
JoinQuery(mainTable string, joinTables []JoinTable, conditions map[string]interface{}, result interface{}) error
|
||||
|
||||
// 事务支持
|
||||
WithTransaction(ctx context.Context, opts *TxOptions, fn func(repo BaseRepository) error) error
|
||||
}
|
||||
|
||||
// 联表定义
|
||||
type JoinTable struct {
|
||||
Table string
|
||||
JoinType string // "INNER", "LEFT", "RIGHT"
|
||||
OnCondition string
|
||||
}
|
||||
|
||||
// 数据库连接接口
|
||||
type DatabaseConnection interface {
|
||||
//AutoMigrate(models ...interface{}) error
|
||||
}
|
||||
|
||||
// 工厂接口
|
||||
type RepositoryFactory interface {
|
||||
CreateConnection() DatabaseConnection
|
||||
CreateRepository() BaseRepository
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package dbfactory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/qiniu/qmgo"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type DatabaseConfig struct {
|
||||
DBType string `json:"dbType"` // mysql/mongodb/sqlite/postgresql
|
||||
MySQL struct {
|
||||
Host string `json:"host"`
|
||||
Port string `json:"port"`
|
||||
User string `json:"user"`
|
||||
Password string `json:"password"`
|
||||
DBName string `json:"dbname"`
|
||||
} `json:"mysql"`
|
||||
MongoDB struct {
|
||||
URI string `json:"uri"`
|
||||
Database string `json:"database"`
|
||||
} `json:"mongodb"`
|
||||
SQLite struct {
|
||||
Path string `json:"path"` // 数据库文件路径
|
||||
} `json:"sqlite"`
|
||||
PostgreSQL struct {
|
||||
Host string `json:"host"`
|
||||
Port string `json:"port"`
|
||||
User string `json:"user"`
|
||||
Password string `json:"password"`
|
||||
DBName string `json:"dbname"`
|
||||
SSLMode string `json:"sslmode"` // disable/require
|
||||
} `json:"postgresql"`
|
||||
}
|
||||
|
||||
var (
|
||||
MySQLDB *gorm.DB
|
||||
PostgreSQLDB *gorm.DB
|
||||
SQLiteDB *gorm.DB
|
||||
MongoDB *qmgo.Database
|
||||
AppConfig DatabaseConfig
|
||||
)
|
||||
var Db BaseRepository
|
||||
|
||||
func LoadConfig() error {
|
||||
data, err := os.ReadFile("config/database.json")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(data, &AppConfig)
|
||||
}
|
||||
func InitDatabase() error {
|
||||
// 加载配置并初始化数据库
|
||||
if err := LoadConfig(); err != nil {
|
||||
log.Fatal("Failed to load config:", err)
|
||||
return err
|
||||
}
|
||||
|
||||
switch AppConfig.DBType {
|
||||
case "mongodb":
|
||||
if err := InitMongoDB(); err != nil {
|
||||
log.Fatal("Failed to connect to MongoDB:", err)
|
||||
return err
|
||||
}
|
||||
Db = NewMongoDBFactory().CreateRepository()
|
||||
case "sqlite":
|
||||
if err := InitSQLite(); err != nil {
|
||||
log.Fatal("Failed to connect to SQLite:", err)
|
||||
return err
|
||||
}
|
||||
Db = NewSQLiteFactory().CreateRepository()
|
||||
case "postgresql":
|
||||
if err := InitPostgreSQL(); err != nil {
|
||||
log.Fatal("Failed to connect to PostgreSQL:", err)
|
||||
return err
|
||||
}
|
||||
Db = NewPostgreSQLFactory().CreateRepository()
|
||||
default:
|
||||
if err := InitMySQL(); err != nil {
|
||||
log.Fatal("Failed to connect to MySQL:", err)
|
||||
return err
|
||||
}
|
||||
Db = NewMySQLFactory().CreateRepository()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func InitMySQL() error {
|
||||
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
|
||||
AppConfig.MySQL.User,
|
||||
AppConfig.MySQL.Password,
|
||||
AppConfig.MySQL.Host,
|
||||
AppConfig.MySQL.Port,
|
||||
AppConfig.MySQL.DBName)
|
||||
|
||||
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
MySQLDB = db
|
||||
log.Println("MySQL connected successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
func InitPostgreSQL() error {
|
||||
dsn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s",
|
||||
AppConfig.PostgreSQL.Host,
|
||||
AppConfig.PostgreSQL.Port,
|
||||
AppConfig.PostgreSQL.User,
|
||||
AppConfig.PostgreSQL.Password,
|
||||
AppConfig.PostgreSQL.DBName,
|
||||
AppConfig.PostgreSQL.SSLMode)
|
||||
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
PostgreSQLDB = db
|
||||
log.Println("PostgreSQL connected successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
func InitSQLite() error {
|
||||
db, err := gorm.Open(sqlite.Open(AppConfig.SQLite.Path), &gorm.Config{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
SQLiteDB = db
|
||||
log.Println("SQLite connected successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
func InitMongoDB() error {
|
||||
ctx := context.Background()
|
||||
client, err := qmgo.NewClient(ctx, &qmgo.Config{Uri: AppConfig.MongoDB.URI})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
db := client.Database(AppConfig.MongoDB.Database)
|
||||
MongoDB = db
|
||||
log.Println("MongoDB connected successfully")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package dbfactory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
|
||||
"github.com/qiniu/qmgo"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
)
|
||||
|
||||
// MongoDB工厂实现
|
||||
type MongoDBFactory struct{}
|
||||
|
||||
func NewMongoDBFactory() *MongoDBFactory {
|
||||
return &MongoDBFactory{}
|
||||
}
|
||||
|
||||
func (f *MongoDBFactory) CreateConnection() DatabaseConnection {
|
||||
return MongoDB
|
||||
}
|
||||
|
||||
func (f *MongoDBFactory) CreateRepository() BaseRepository {
|
||||
return &mongoRepository{
|
||||
client: MongoDB,
|
||||
}
|
||||
}
|
||||
|
||||
type mongoRepository struct {
|
||||
client *qmgo.Database
|
||||
}
|
||||
|
||||
func (r *mongoRepository) Create(table string, entity interface{}) error {
|
||||
_, err := r.client.Collection(table).InsertOne(context.Background(), entity)
|
||||
return err
|
||||
}
|
||||
func (r *mongoRepository) Count(table string, conditions map[string]interface{}) (int64, error) {
|
||||
// 使用 CountDocuments 替代 Count
|
||||
count, err := r.client.Collection(table).Find(context.Background(), bson.M(conditions)).Count()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
func (r *mongoRepository) GetByID(table string, id interface{}, result interface{}) error {
|
||||
return r.client.Collection(table).Find(context.Background(), map[string]interface{}{"_id": id}).One(result)
|
||||
}
|
||||
|
||||
func (r *mongoRepository) Update(table string, entity interface{}) error {
|
||||
return r.client.Collection(table).UpdateOne(context.Background(), map[string]interface{}{"_id": getIdFromEntity(entity)}, entity)
|
||||
}
|
||||
|
||||
func (r *mongoRepository) Delete(table string, id interface{}) error {
|
||||
return r.client.Collection(table).Remove(context.Background(), map[string]interface{}{"_id": id})
|
||||
}
|
||||
|
||||
func getIdFromEntity(entity interface{}) interface{} {
|
||||
// 获取entity的反射值
|
||||
val := reflect.ValueOf(entity)
|
||||
|
||||
// 确保传入的是一个结构体指针
|
||||
if val.Kind() != reflect.Ptr || val.Elem().Kind() != reflect.Struct {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 获取结构体的反射类型
|
||||
elemType := val.Elem().Type()
|
||||
|
||||
// 查找名为"_id"的字段
|
||||
field, found := elemType.FieldByName("_id")
|
||||
if !found {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 获取字段的值
|
||||
id := val.Elem().FieldByName(field.Name)
|
||||
|
||||
// 返回字段的值
|
||||
return id.Interface()
|
||||
}
|
||||
|
||||
func (r *mongoRepository) BatchCreate(table string, entities []interface{}) error {
|
||||
_, err := r.client.Collection(table).InsertMany(context.Background(), entities)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *mongoRepository) BatchDelete(table string, ids []interface{}) error {
|
||||
_, err := r.client.Collection(table).RemoveAll(context.Background(), bson.M{"_id": bson.M{"$in": ids}})
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *mongoRepository) JoinQuery(mainTable string, joinTables []JoinTable, conditions map[string]interface{}, result interface{}) error {
|
||||
// MongoDB需要特殊处理联表查询
|
||||
// 这里实现$lookup聚合查询
|
||||
pipeline := []bson.M{
|
||||
{"$match": conditions},
|
||||
}
|
||||
for _, join := range joinTables {
|
||||
pipeline = append(pipeline, bson.M{
|
||||
"$lookup": bson.M{
|
||||
"from": join.Table,
|
||||
"localField": "_id",
|
||||
"foreignField": "_id",
|
||||
"as": join.Table,
|
||||
},
|
||||
})
|
||||
}
|
||||
return r.client.Collection(mainTable).Aggregate(context.Background(), pipeline).All(result)
|
||||
}
|
||||
|
||||
func (r *mongoRepository) GetOne(table string, conditions map[string]interface{}, result interface{}) error {
|
||||
return r.client.Collection(table).Find(context.Background(), conditions).One(result)
|
||||
}
|
||||
|
||||
func (r *mongoRepository) GetList(table string, conditions map[string]interface{}, result interface{}) error {
|
||||
return r.client.Collection(table).Find(context.Background(), conditions).All(result)
|
||||
}
|
||||
|
||||
func (r *mongoRepository) GetPage(table string, conditions map[string]interface{}, pageParams PageParams, result *PageResult) error {
|
||||
// 获取总数
|
||||
total, err := r.client.Collection(table).Find(context.Background(), conditions).Count()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 设置分页选项(使用 qmgo 的链式调用)
|
||||
findOptions := r.client.Collection(table).Find(context.Background(), conditions).
|
||||
Skip(int64((pageParams.Page - 1) * pageParams.PageSize)).
|
||||
Limit(int64(pageParams.PageSize))
|
||||
|
||||
if pageParams.OrderBy != "" {
|
||||
findOptions = findOptions.Sort(pageParams.OrderBy)
|
||||
}
|
||||
|
||||
// 执行查询
|
||||
var data []interface{} // 假设 result.Data 是一个切片
|
||||
if err := findOptions.All(&data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 将数据赋值给 result.Data
|
||||
result.Data = data
|
||||
result.Total = total
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *mongoRepository) AutoMigrate(models ...interface{}) error {
|
||||
// MongoDB不需要显式迁移,返回nil即可
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *mongoRepository) WithTransaction(ctx context.Context, opts *TxOptions, fn func(repo BaseRepository) error) error {
|
||||
// // 获取 qmgo.Client
|
||||
// client := r.client.Client()
|
||||
// if client == nil {
|
||||
// return fmt.Errorf("client is nil")
|
||||
// }
|
||||
|
||||
// // 定义事务回调函数
|
||||
// callback := func(sessCtx context.Context) (interface{}, error) {
|
||||
// // 创建一个新的 mongoRepository 实例,使用 sessCtx 作为上下文
|
||||
// txRepo := &mongoRepository{client: r.client}
|
||||
// return nil, fn(txRepo)
|
||||
// }
|
||||
|
||||
// // 设置事务选项
|
||||
// transactionOpts := options.Transaction()
|
||||
// switch opts.Isolation {
|
||||
// case LevelReadUncommitted:
|
||||
// transactionOpts = transactionOpts.SetReadConcern(options.ReadConcern{}.SetLevel("local"))
|
||||
// case LevelReadCommitted:
|
||||
// transactionOpts = transactionOpts.SetReadConcern(options.ReadConcern{}.SetLevel("majority"))
|
||||
// case LevelRepeatableRead:
|
||||
// transactionOpts = transactionOpts.SetReadConcern(options.ReadConcern{}.SetLevel("snapshot"))
|
||||
// case LevelSerializable:
|
||||
// transactionOpts = transactionOpts.SetReadConcern(options.ReadConcern{}.SetLevel("linearizable"))
|
||||
// }
|
||||
// if opts.ReadOnly {
|
||||
// transactionOpts = transactionOpts.SetReadOnly(true)
|
||||
// }
|
||||
|
||||
// // 执行事务
|
||||
// result, err := client.DoTransaction(ctx, callback, transactionOpts)
|
||||
// if err == qmgo.ErrTransactionRetry {
|
||||
// return r.WithTransaction(ctx, opts, fn)
|
||||
// }
|
||||
|
||||
// return err
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package dbfactory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// MySQL工厂实现
|
||||
type MySQLFactory struct{}
|
||||
|
||||
func NewMySQLFactory() *MySQLFactory {
|
||||
return &MySQLFactory{}
|
||||
}
|
||||
|
||||
func (f *MySQLFactory) CreateConnection() DatabaseConnection {
|
||||
return MySQLDB
|
||||
}
|
||||
|
||||
func (f *MySQLFactory) CreateRepository() BaseRepository {
|
||||
return &mysqlRepository{
|
||||
db: MySQLDB,
|
||||
}
|
||||
}
|
||||
|
||||
type mysqlRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (c *mysqlRepository) AutoMigrate(models ...interface{}) error {
|
||||
return c.db.AutoMigrate(models...)
|
||||
}
|
||||
func (r *mysqlRepository) Create(table string, entity interface{}) error {
|
||||
return r.db.Table(table).Create(entity).Error
|
||||
}
|
||||
func (r *mysqlRepository) Count(table string, conditions map[string]interface{}) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.Table(table).Where(conditions).Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
func (r *mysqlRepository) GetByID(table string, id interface{}, result interface{}) error {
|
||||
return r.db.Table(table).First(result, id).Error
|
||||
}
|
||||
|
||||
func (r *mysqlRepository) Update(table string, entity interface{}) error {
|
||||
return r.db.Table(table).Save(entity).Error
|
||||
}
|
||||
|
||||
func (r *mysqlRepository) Delete(table string, id interface{}) error {
|
||||
return r.db.Table(table).Delete(nil, id).Error
|
||||
}
|
||||
|
||||
func (r *mysqlRepository) BatchCreate(table string, entities []interface{}) error {
|
||||
return r.db.Table(table).CreateInBatches(entities, len(entities)).Error
|
||||
}
|
||||
|
||||
func (r *mysqlRepository) BatchDelete(table string, ids []interface{}) error {
|
||||
return r.db.Table(table).Delete(nil, ids).Error
|
||||
}
|
||||
|
||||
func (r *mysqlRepository) JoinQuery(mainTable string, joinTables []JoinTable, conditions map[string]interface{}, result interface{}) error {
|
||||
tx := r.db.Table(mainTable)
|
||||
for _, join := range joinTables {
|
||||
tx = tx.Joins(join.JoinType + " JOIN " + join.Table + " ON " + join.OnCondition)
|
||||
}
|
||||
return tx.Where(conditions).Find(result).Error
|
||||
}
|
||||
|
||||
func (r *mysqlRepository) GetOne(table string, conditions map[string]interface{}, result interface{}) error {
|
||||
return r.db.Table(table).Where(conditions).First(result).Error
|
||||
}
|
||||
|
||||
func (r *mysqlRepository) GetList(table string, conditions map[string]interface{}, result interface{}) error {
|
||||
return r.db.Table(table).Where(conditions).Find(result).Error
|
||||
}
|
||||
|
||||
func (r *mysqlRepository) GetPage(table string, conditions map[string]interface{}, pageParams PageParams, result *PageResult) error {
|
||||
var total int64
|
||||
if err := r.db.Table(table).Where(conditions).Count(&total).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
query := r.db.Table(table).Where(conditions)
|
||||
if pageParams.OrderBy != "" {
|
||||
query = query.Order(pageParams.OrderBy)
|
||||
}
|
||||
if err := query.Offset((pageParams.Page - 1) * pageParams.PageSize).
|
||||
Limit(pageParams.PageSize).
|
||||
Find(result.Data).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
result.Total = total
|
||||
return nil
|
||||
}
|
||||
func (r *mysqlRepository) WithTransaction(ctx context.Context, opts *TxOptions, fn func(repo BaseRepository) error) error {
|
||||
txOpts := &sql.TxOptions{}
|
||||
switch opts.Isolation {
|
||||
case LevelReadUncommitted:
|
||||
txOpts.Isolation = sql.LevelReadUncommitted
|
||||
case LevelReadCommitted:
|
||||
txOpts.Isolation = sql.LevelReadCommitted
|
||||
case LevelRepeatableRead:
|
||||
txOpts.Isolation = sql.LevelRepeatableRead
|
||||
case LevelSerializable:
|
||||
txOpts.Isolation = sql.LevelSerializable
|
||||
}
|
||||
txOpts.ReadOnly = opts.ReadOnly
|
||||
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
return fn(&mysqlRepository{db: tx.WithContext(ctx)})
|
||||
}, txOpts)
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package dbfactory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type PostgreSQLFactory struct{}
|
||||
|
||||
func NewPostgreSQLFactory() *PostgreSQLFactory {
|
||||
return &PostgreSQLFactory{}
|
||||
}
|
||||
|
||||
func (f *PostgreSQLFactory) CreateConnection() DatabaseConnection {
|
||||
return &postgresqlConnection{
|
||||
db: PostgreSQLDB,
|
||||
}
|
||||
}
|
||||
|
||||
func (f *PostgreSQLFactory) CreateRepository() BaseRepository {
|
||||
return &postgresqlRepository{
|
||||
db: PostgreSQLDB,
|
||||
}
|
||||
}
|
||||
|
||||
type postgresqlConnection struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (c *postgresqlConnection) AutoMigrate(models ...interface{}) error {
|
||||
return c.db.AutoMigrate(models...)
|
||||
}
|
||||
|
||||
type postgresqlRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (r *postgresqlRepository) Create(table string, entity interface{}) error {
|
||||
return r.db.Table(table).Create(entity).Error
|
||||
}
|
||||
func (r *postgresqlRepository) Count(table string, conditions map[string]interface{}) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.Table(table).Where(conditions).Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
func (r *postgresqlRepository) GetByID(table string, id interface{}, result interface{}) error {
|
||||
return r.db.Table(table).First(result, id).Error
|
||||
}
|
||||
|
||||
func (r *postgresqlRepository) Update(table string, entity interface{}) error {
|
||||
return r.db.Table(table).Save(entity).Error
|
||||
}
|
||||
|
||||
func (r *postgresqlRepository) Delete(table string, id interface{}) error {
|
||||
return r.db.Table(table).Delete(nil, id).Error
|
||||
}
|
||||
|
||||
func (r *postgresqlRepository) GetOne(table string, conditions map[string]interface{}, result interface{}) error {
|
||||
return r.db.Table(table).Where(conditions).First(result).Error
|
||||
}
|
||||
|
||||
func (r *postgresqlRepository) GetList(table string, conditions map[string]interface{}, result interface{}) error {
|
||||
return r.db.Table(table).Where(conditions).Find(result).Error
|
||||
}
|
||||
|
||||
func (r *postgresqlRepository) GetPage(table string, conditions map[string]interface{}, pageParams PageParams, result *PageResult) error {
|
||||
var total int64
|
||||
if err := r.db.Table(table).Where(conditions).Count(&total).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
query := r.db.Table(table).Where(conditions)
|
||||
if pageParams.OrderBy != "" {
|
||||
query = query.Order(pageParams.OrderBy)
|
||||
}
|
||||
if err := query.Offset((pageParams.Page - 1) * pageParams.PageSize).
|
||||
Limit(pageParams.PageSize).
|
||||
Find(result.Data).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
result.Total = total
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *postgresqlRepository) BatchCreate(table string, entities []interface{}) error {
|
||||
return r.db.Table(table).CreateInBatches(entities, len(entities)).Error
|
||||
}
|
||||
|
||||
func (r *postgresqlRepository) BatchDelete(table string, ids []interface{}) error {
|
||||
return r.db.Table(table).Delete(nil, ids).Error
|
||||
}
|
||||
|
||||
func (r *postgresqlRepository) JoinQuery(mainTable string, joinTables []JoinTable, conditions map[string]interface{}, result interface{}) error {
|
||||
tx := r.db.Table(mainTable)
|
||||
for _, join := range joinTables {
|
||||
tx = tx.Joins(join.JoinType + " JOIN " + join.Table + " ON " + join.OnCondition)
|
||||
}
|
||||
return tx.Where(conditions).Find(result).Error
|
||||
}
|
||||
|
||||
// PostgreSQL特有功能:JSONB操作
|
||||
func (r *postgresqlRepository) JSONBContains(table, column, path string, value interface{}, result interface{}) error {
|
||||
return r.db.Table(table).Where(column+"::jsonb @> ?", `{"`+path+`":`+value.(string)+`}`).Find(result).Error
|
||||
}
|
||||
|
||||
func (r *postgresqlRepository) AutoMigrate(models ...interface{}) error {
|
||||
return r.db.AutoMigrate(models...)
|
||||
}
|
||||
|
||||
// 事务支持
|
||||
func (r *postgresqlRepository) WithTransaction(ctx context.Context, opts *TxOptions, fn func(repo BaseRepository) error) error {
|
||||
txOpts := &sql.TxOptions{}
|
||||
switch opts.Isolation {
|
||||
case LevelReadUncommitted:
|
||||
txOpts.Isolation = sql.LevelReadUncommitted
|
||||
case LevelReadCommitted:
|
||||
txOpts.Isolation = sql.LevelReadCommitted
|
||||
case LevelRepeatableRead:
|
||||
txOpts.Isolation = sql.LevelRepeatableRead
|
||||
case LevelSerializable:
|
||||
txOpts.Isolation = sql.LevelSerializable
|
||||
}
|
||||
txOpts.ReadOnly = opts.ReadOnly
|
||||
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
return fn(&postgresqlRepository{db: tx.WithContext(ctx)})
|
||||
}, txOpts)
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package dbfactory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type SQLiteFactory struct{}
|
||||
|
||||
func NewSQLiteFactory() *SQLiteFactory {
|
||||
return &SQLiteFactory{}
|
||||
}
|
||||
|
||||
func (f *SQLiteFactory) CreateConnection() DatabaseConnection {
|
||||
return &sqliteConnection{
|
||||
db: SQLiteDB,
|
||||
}
|
||||
}
|
||||
|
||||
func (f *SQLiteFactory) CreateRepository() BaseRepository {
|
||||
return &sqliteRepository{
|
||||
db: SQLiteDB,
|
||||
}
|
||||
}
|
||||
|
||||
type sqliteConnection struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (c *sqliteConnection) AutoMigrate(models ...interface{}) error {
|
||||
return c.db.AutoMigrate(models...)
|
||||
}
|
||||
|
||||
type sqliteRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) Create(table string, entity interface{}) error {
|
||||
return r.db.Table(table).Create(entity).Error
|
||||
}
|
||||
func (r *sqliteRepository) Count(table string, conditions map[string]interface{}) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.Table(table).Where(conditions).Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
func (r *sqliteRepository) GetByID(table string, id interface{}, result interface{}) error {
|
||||
return r.db.Table(table).First(result, id).Error
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) Update(table string, entity interface{}) error {
|
||||
return r.db.Table(table).Save(entity).Error
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) Delete(table string, id interface{}) error {
|
||||
return r.db.Table(table).Delete(nil, id).Error
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) GetOne(table string, conditions map[string]interface{}, result interface{}) error {
|
||||
return r.db.Table(table).Where(conditions).First(result).Error
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) GetList(table string, conditions map[string]interface{}, result interface{}) error {
|
||||
return r.db.Table(table).Where(conditions).Find(result).Error
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) GetPage(table string, conditions map[string]interface{}, pageParams PageParams, result *PageResult) error {
|
||||
var total int64
|
||||
if err := r.db.Table(table).Where(conditions).Count(&total).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
query := r.db.Table(table).Where(conditions)
|
||||
if pageParams.OrderBy != "" {
|
||||
query = query.Order(pageParams.OrderBy)
|
||||
}
|
||||
if err := query.Offset((pageParams.Page - 1) * pageParams.PageSize).
|
||||
Limit(pageParams.PageSize).
|
||||
Find(result.Data).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
result.Total = total
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) BatchCreate(table string, entities []interface{}) error {
|
||||
return r.db.Table(table).CreateInBatches(entities, len(entities)).Error
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) BatchDelete(table string, ids []interface{}) error {
|
||||
return r.db.Table(table).Delete(nil, ids).Error
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) JoinQuery(mainTable string, joinTables []JoinTable, conditions map[string]interface{}, result interface{}) error {
|
||||
tx := r.db.Table(mainTable)
|
||||
for _, join := range joinTables {
|
||||
tx = tx.Joins(join.JoinType + " JOIN " + join.Table + " ON " + join.OnCondition)
|
||||
}
|
||||
return tx.Where(conditions).Find(result).Error
|
||||
}
|
||||
func (r *sqliteRepository) AutoMigrate(models ...interface{}) error {
|
||||
return r.db.AutoMigrate(models...)
|
||||
}
|
||||
|
||||
// 事务支持
|
||||
func (r *sqliteRepository) WithTransaction(ctx context.Context, opts *TxOptions, fn func(repo BaseRepository) error) error {
|
||||
txOpts := &sql.TxOptions{}
|
||||
switch opts.Isolation {
|
||||
case LevelReadUncommitted:
|
||||
txOpts.Isolation = sql.LevelReadUncommitted
|
||||
case LevelReadCommitted:
|
||||
txOpts.Isolation = sql.LevelReadCommitted
|
||||
case LevelRepeatableRead:
|
||||
txOpts.Isolation = sql.LevelRepeatableRead
|
||||
case LevelSerializable:
|
||||
txOpts.Isolation = sql.LevelSerializable
|
||||
}
|
||||
txOpts.ReadOnly = opts.ReadOnly
|
||||
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
return fn(&sqliteRepository{db: tx.WithContext(ctx)})
|
||||
}, txOpts)
|
||||
}
|
||||
Binary file not shown.
Reference in New Issue
Block a user