feat: add SproutWorkCollect apps
This commit is contained in:
4
SproutWorkCollect-Backend-Golang/.dockerignore
Normal file
4
SproutWorkCollect-Backend-Golang/.dockerignore
Normal file
@@ -0,0 +1,4 @@
|
||||
data/
|
||||
*.tmp
|
||||
.git
|
||||
*.md
|
||||
40
SproutWorkCollect-Backend-Golang/Dockerfile
Normal file
40
SproutWorkCollect-Backend-Golang/Dockerfile
Normal file
@@ -0,0 +1,40 @@
|
||||
# ─── Build Stage ──────────────────────────────────────────────────────────────
|
||||
FROM golang:1.21-alpine AS builder
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
# Allow go to fetch modules even without a pre-generated go.sum
|
||||
ENV GOFLAGS=-mod=mod
|
||||
ENV GONOSUMDB=*
|
||||
|
||||
COPY go.mod ./
|
||||
RUN go mod download
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
|
||||
go build -ldflags="-w -s" -o sproutworkcollect-backend .
|
||||
|
||||
# ─── Runtime Stage ────────────────────────────────────────────────────────────
|
||||
FROM alpine:3.19
|
||||
|
||||
RUN apk add --no-cache ca-certificates tzdata wget && \
|
||||
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
|
||||
echo "Asia/Shanghai" > /etc/timezone
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=builder /build/sproutworkcollect-backend .
|
||||
|
||||
# Default data directories; override by mounting volumes at runtime
|
||||
RUN mkdir -p /data/works /data/config
|
||||
|
||||
EXPOSE 5000
|
||||
|
||||
ENV SPROUTWORKCOLLECT_DATA_DIR=/data
|
||||
ENV PORT=5000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=15s --retries=3 \
|
||||
CMD wget -qO- http://localhost:5000/api/settings || exit 1
|
||||
|
||||
CMD ["./sproutworkcollect-backend"]
|
||||
29
SproutWorkCollect-Backend-Golang/docker-compose.yml
Normal file
29
SproutWorkCollect-Backend-Golang/docker-compose.yml
Normal file
@@ -0,0 +1,29 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
sproutworkcollect-api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: sproutworkcollect-backend-go
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${SPROUTWORKCOLLECT_PORT:-5000}:5000"
|
||||
environment:
|
||||
- PORT=5000
|
||||
- SPROUTWORKCOLLECT_DATA_DIR=/data
|
||||
# Override the default admin token (strongly recommended in production):
|
||||
# - ADMIN_TOKEN=your_secure_token_here
|
||||
# Enable verbose Gin logging (set to 1 for debugging):
|
||||
# - GIN_DEBUG=0
|
||||
volumes:
|
||||
# 默认挂载项目目录下的 data/,部署到服务器时设置 SPROUTWORKCOLLECT_DATA_PATH 覆盖
|
||||
# 例如:export SPROUTWORKCOLLECT_DATA_PATH=/shumengya/docker/sproutworkcollect/data
|
||||
- "${SPROUTWORKCOLLECT_DATA_PATH:-./data}/works:/data/works"
|
||||
- "${SPROUTWORKCOLLECT_DATA_PATH:-./data}/config:/data/config"
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://localhost:5000/api/settings"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 15s
|
||||
37
SproutWorkCollect-Backend-Golang/go.mod
Normal file
37
SproutWorkCollect-Backend-Golang/go.mod
Normal file
@@ -0,0 +1,37 @@
|
||||
module sproutworkcollect-backend
|
||||
|
||||
go 1.21
|
||||
|
||||
require (
|
||||
github.com/gin-contrib/cors v1.5.0
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bytedance/sonic v1.10.1 // indirect
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
|
||||
github.com/chenzhuoyu/iasm v0.9.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
|
||||
github.com/gin-contrib/sse v0.1.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.15.5 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.5 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/leodido/go-urn v1.2.4 // indirect
|
||||
github.com/mattn/go-isatty v0.0.19 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.11 // indirect
|
||||
golang.org/x/arch v0.5.0 // indirect
|
||||
golang.org/x/crypto v0.14.0 // indirect
|
||||
golang.org/x/net v0.16.0 // indirect
|
||||
golang.org/x/sys v0.13.0 // indirect
|
||||
golang.org/x/text v0.13.0 // indirect
|
||||
google.golang.org/protobuf v1.31.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
102
SproutWorkCollect-Backend-Golang/go.sum
Normal file
102
SproutWorkCollect-Backend-Golang/go.sum
Normal file
@@ -0,0 +1,102 @@
|
||||
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
|
||||
github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM=
|
||||
github.com/bytedance/sonic v1.10.1 h1:7a1wuFXL1cMy7a3f7/VFcEtriuXQnUBhtoVfOZiaysc=
|
||||
github.com/bytedance/sonic v1.10.1/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA=
|
||||
github.com/chenzhuoyu/iasm v0.9.0 h1:9fhXjVzq5hUy2gkhhgHl95zG2cEAhw9OSGs8toWWAwo=
|
||||
github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
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/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
|
||||
github.com/gin-contrib/cors v1.5.0 h1:DgGKV7DDoOn36DFkNtbHrjoRiT5ExCe+PC9/xp7aKvk=
|
||||
github.com/gin-contrib/cors v1.5.0/go.mod h1:TvU7MAZ3EwrPLI2ztzTt3tqgvBCq+wn8WpZmfADjupI=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
|
||||
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
|
||||
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.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.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.15.5 h1:LEBecTWb/1j5TNY1YYG2RcOUN3R7NLylN+x8TTueE24=
|
||||
github.com/go-playground/validator/v10 v10.15.5/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
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/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.5 h1:0E5MSMDEoAulmXNFquVs//DdoomxaoTY1kUhbc/qbZg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.5/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||
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.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
|
||||
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
|
||||
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
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/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4=
|
||||
github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
|
||||
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/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
|
||||
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
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/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
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.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
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.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
|
||||
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/arch v0.5.0 h1:jpGode6huXQxcskEIpOCvrU+tzo81b6+oFLUYXWtH/Y=
|
||||
golang.org/x/arch v0.5.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
|
||||
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
|
||||
golang.org/x/net v0.16.0 h1:7eBu7KsSvFDtSXUIDbh3aqlK4DPsZ1rByC8PFfBThos=
|
||||
golang.org/x/net v0.16.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
|
||||
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.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
|
||||
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
|
||||
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/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/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=
|
||||
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
79
SproutWorkCollect-Backend-Golang/internal/config/config.go
Normal file
79
SproutWorkCollect-Backend-Golang/internal/config/config.go
Normal file
@@ -0,0 +1,79 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Config holds all runtime configuration resolved from environment variables.
|
||||
type Config struct {
|
||||
Port int
|
||||
AdminToken string
|
||||
WorksDir string
|
||||
ConfigDir string
|
||||
Debug bool
|
||||
}
|
||||
|
||||
// Load reads environment variables and returns a fully-populated Config.
|
||||
//
|
||||
// Directory resolution priority:
|
||||
// 1. SPROUTWORKCOLLECT_WORKS_DIR / SPROUTWORKCOLLECT_CONFIG_DIR (per-dir override)
|
||||
// 2. SPROUTWORKCOLLECT_DATA_DIR / DATA_DIR (data root, works/ and config/ appended)
|
||||
// 3. ./data/works and ./data/config (relative to current working directory)
|
||||
func Load() *Config {
|
||||
cfg := &Config{
|
||||
Port: 5000,
|
||||
// Do not commit real admin tokens; override via ADMIN_TOKEN / SPROUTWORKCOLLECT_ADMIN_TOKEN.
|
||||
AdminToken: "change-me",
|
||||
}
|
||||
|
||||
if v := os.Getenv("PORT"); v != "" {
|
||||
if p, err := strconv.Atoi(v); err == nil {
|
||||
cfg.Port = p
|
||||
}
|
||||
}
|
||||
|
||||
if v := firstEnv("SPROUTWORKCOLLECT_ADMIN_TOKEN", "ADMIN_TOKEN"); v != "" {
|
||||
cfg.AdminToken = v
|
||||
}
|
||||
|
||||
dbg := os.Getenv("GIN_DEBUG")
|
||||
cfg.Debug = dbg == "1" || dbg == "true"
|
||||
|
||||
dataDir := firstEnv("SPROUTWORKCOLLECT_DATA_DIR", "DATA_DIR")
|
||||
|
||||
worksDir := firstEnv("SPROUTWORKCOLLECT_WORKS_DIR", "WORKS_DIR")
|
||||
if worksDir == "" {
|
||||
if dataDir != "" {
|
||||
worksDir = filepath.Join(dataDir, "works")
|
||||
} else {
|
||||
wd, _ := os.Getwd()
|
||||
worksDir = filepath.Join(wd, "data", "works")
|
||||
}
|
||||
}
|
||||
|
||||
configDir := firstEnv("SPROUTWORKCOLLECT_CONFIG_DIR", "CONFIG_DIR")
|
||||
if configDir == "" {
|
||||
if dataDir != "" {
|
||||
configDir = filepath.Join(dataDir, "config")
|
||||
} else {
|
||||
wd, _ := os.Getwd()
|
||||
configDir = filepath.Join(wd, "data", "config")
|
||||
}
|
||||
}
|
||||
|
||||
cfg.WorksDir = filepath.Clean(worksDir)
|
||||
cfg.ConfigDir = filepath.Clean(configDir)
|
||||
|
||||
return cfg
|
||||
}
|
||||
|
||||
func firstEnv(keys ...string) string {
|
||||
for _, k := range keys {
|
||||
if v := os.Getenv(k); v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
317
SproutWorkCollect-Backend-Golang/internal/handler/admin.go
Normal file
317
SproutWorkCollect-Backend-Golang/internal/handler/admin.go
Normal file
@@ -0,0 +1,317 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"sproutworkcollect-backend/internal/model"
|
||||
"sproutworkcollect-backend/internal/service"
|
||||
)
|
||||
|
||||
const maxUploadBytes = 5000 << 20 // 5 000 MB
|
||||
|
||||
// AdminHandler handles admin-only API endpoints (protected by AdminAuth middleware).
|
||||
type AdminHandler struct {
|
||||
workSvc *service.WorkService
|
||||
}
|
||||
|
||||
// NewAdminHandler wires up an AdminHandler.
|
||||
func NewAdminHandler(workSvc *service.WorkService) *AdminHandler {
|
||||
return &AdminHandler{workSvc: workSvc}
|
||||
}
|
||||
|
||||
// GetWorks handles GET /api/admin/works
|
||||
func (h *AdminHandler) GetWorks(c *gin.Context) {
|
||||
works, err := h.workSvc.LoadAllWorks()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
responses := make([]*model.WorkResponse, len(works))
|
||||
for i, w := range works {
|
||||
responses[i] = h.workSvc.BuildResponse(w)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": responses, "total": len(responses)})
|
||||
}
|
||||
|
||||
// CreateWork handles POST /api/admin/works
|
||||
func (h *AdminHandler) CreateWork(c *gin.Context) {
|
||||
var data model.WorkConfig
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "请求数据格式错误"})
|
||||
return
|
||||
}
|
||||
if data.WorkID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "作品ID不能为空"})
|
||||
return
|
||||
}
|
||||
|
||||
ts := time.Now().Format("2006-01-02T15:04:05.000000")
|
||||
data.UploadTime = ts
|
||||
data.UpdateTime = ts
|
||||
data.UpdateCount = 0
|
||||
data.Downloads = 0
|
||||
data.Views = 0
|
||||
data.Likes = 0
|
||||
data.Normalize()
|
||||
|
||||
if err := h.workSvc.CreateWork(&data); err != nil {
|
||||
status := http.StatusInternalServerError
|
||||
if strings.Contains(err.Error(), "已存在") {
|
||||
status = http.StatusConflict
|
||||
}
|
||||
c.JSON(status, gin.H{"success": false, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "创建成功", "work_id": data.WorkID})
|
||||
}
|
||||
|
||||
// UpdateWork handles PUT /api/admin/works/:work_id
|
||||
func (h *AdminHandler) UpdateWork(c *gin.Context) {
|
||||
workID := c.Param("work_id")
|
||||
var data model.WorkConfig
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "请求数据格式错误"})
|
||||
return
|
||||
}
|
||||
if err := h.workSvc.UpdateWork(workID, &data); err != nil {
|
||||
status := http.StatusInternalServerError
|
||||
if strings.Contains(err.Error(), "不存在") {
|
||||
status = http.StatusNotFound
|
||||
}
|
||||
c.JSON(status, gin.H{"success": false, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "更新成功"})
|
||||
}
|
||||
|
||||
// DeleteWork handles DELETE /api/admin/works/:work_id
|
||||
func (h *AdminHandler) DeleteWork(c *gin.Context) {
|
||||
if err := h.workSvc.DeleteWork(c.Param("work_id")); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"success": false, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "删除成功"})
|
||||
}
|
||||
|
||||
// UploadFile handles POST /api/admin/upload/:work_id/:file_type
|
||||
// file_type: "image" | "video" | "platform"
|
||||
// For "platform", the form field "platform" must specify the target platform name.
|
||||
func (h *AdminHandler) UploadFile(c *gin.Context) {
|
||||
workID := c.Param("work_id")
|
||||
fileType := c.Param("file_type")
|
||||
|
||||
if !h.workSvc.WorkExists(workID) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"success": false, "message": "作品不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
fh, err := c.FormFile("file")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "没有文件"})
|
||||
return
|
||||
}
|
||||
if fh.Size > maxUploadBytes {
|
||||
c.JSON(http.StatusRequestEntityTooLarge, gin.H{
|
||||
"success": false,
|
||||
"message": fmt.Sprintf("文件太大,最大支持 %dMB,当前 %dMB",
|
||||
maxUploadBytes>>20, fh.Size>>20),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
originalName := fh.Filename
|
||||
safeName := service.SafeFilename(originalName)
|
||||
ext := strings.ToLower(filepath.Ext(safeName))
|
||||
|
||||
allowed := map[string]bool{
|
||||
".png": true, ".jpg": true, ".jpeg": true, ".gif": true,
|
||||
".mp4": true, ".avi": true, ".mov": true,
|
||||
".zip": true, ".rar": true, ".apk": true, ".exe": true, ".dmg": true,
|
||||
}
|
||||
if !allowed[ext] {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "不支持的文件格式"})
|
||||
return
|
||||
}
|
||||
|
||||
// Determine destination directory and resolve a unique filename.
|
||||
// ModifyWork (called later) re-checks uniqueness under a write lock to avoid races.
|
||||
work, err := h.workSvc.LoadWork(workID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"success": false, "message": "作品配置不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
var saveDir string
|
||||
var platform string
|
||||
|
||||
switch fileType {
|
||||
case "image":
|
||||
saveDir = filepath.Join(h.workSvc.WorksDir(), workID, "image")
|
||||
case "video":
|
||||
saveDir = filepath.Join(h.workSvc.WorksDir(), workID, "video")
|
||||
case "platform":
|
||||
platform = c.PostForm("platform")
|
||||
if platform == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "平台参数缺失"})
|
||||
return
|
||||
}
|
||||
saveDir = filepath.Join(h.workSvc.WorksDir(), workID, "platform", platform)
|
||||
default:
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "不支持的文件类型"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(saveDir, 0755); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "创建目录失败"})
|
||||
return
|
||||
}
|
||||
|
||||
// Pre-compute unique filename based on current state.
|
||||
// The authoritative assignment happens inside ModifyWork below.
|
||||
var previewName string
|
||||
switch fileType {
|
||||
case "image":
|
||||
previewName = service.UniqueFilename(safeName, work.Screenshots)
|
||||
case "video":
|
||||
previewName = service.UniqueFilename(safeName, work.VideoFiles)
|
||||
case "platform":
|
||||
previewName = service.UniqueFilename(safeName, work.FileNames[platform])
|
||||
}
|
||||
|
||||
destPath := filepath.Join(saveDir, previewName)
|
||||
if err := c.SaveUploadedFile(fh, destPath); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"success": false,
|
||||
"message": fmt.Sprintf("保存文件失败: %v", err),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Atomically update the work config under a write lock.
|
||||
var finalName string
|
||||
modErr := h.workSvc.ModifyWork(workID, func(w *model.WorkConfig) {
|
||||
// Re-derive the unique name inside the lock to handle concurrent uploads.
|
||||
switch fileType {
|
||||
case "image":
|
||||
finalName = service.UniqueFilename(safeName, w.Screenshots)
|
||||
case "video":
|
||||
finalName = service.UniqueFilename(safeName, w.VideoFiles)
|
||||
case "platform":
|
||||
finalName = service.UniqueFilename(safeName, w.FileNames[platform])
|
||||
}
|
||||
|
||||
// Rename the file on disk if the finalName differs from the pre-computed one.
|
||||
if finalName != previewName {
|
||||
newDest := filepath.Join(saveDir, finalName)
|
||||
_ = os.Rename(destPath, newDest)
|
||||
}
|
||||
|
||||
if w.OriginalNames == nil {
|
||||
w.OriginalNames = make(map[string]string)
|
||||
}
|
||||
w.OriginalNames[finalName] = originalName
|
||||
|
||||
switch fileType {
|
||||
case "image":
|
||||
if !service.ContainsString(w.Screenshots, finalName) {
|
||||
w.Screenshots = append(w.Screenshots, finalName)
|
||||
}
|
||||
if w.Cover == "" {
|
||||
w.Cover = finalName
|
||||
}
|
||||
case "video":
|
||||
if !service.ContainsString(w.VideoFiles, finalName) {
|
||||
w.VideoFiles = append(w.VideoFiles, finalName)
|
||||
}
|
||||
case "platform":
|
||||
if w.FileNames == nil {
|
||||
w.FileNames = make(map[string][]string)
|
||||
}
|
||||
if !service.ContainsString(w.FileNames[platform], finalName) {
|
||||
w.FileNames[platform] = append(w.FileNames[platform], finalName)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if modErr != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "更新配置失败"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "上传成功",
|
||||
"filename": finalName,
|
||||
"file_size": fh.Size,
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteFile handles DELETE /api/admin/delete-file/:work_id/:file_type/:filename
|
||||
func (h *AdminHandler) DeleteFile(c *gin.Context) {
|
||||
workID := c.Param("work_id")
|
||||
fileType := c.Param("file_type")
|
||||
filename := c.Param("filename")
|
||||
|
||||
if _, err := h.workSvc.LoadWork(workID); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"success": false, "message": "作品不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
platform := c.Query("platform")
|
||||
|
||||
var filePath string
|
||||
switch fileType {
|
||||
case "image":
|
||||
filePath = filepath.Join(h.workSvc.WorksDir(), workID, "image", filename)
|
||||
case "video":
|
||||
filePath = filepath.Join(h.workSvc.WorksDir(), workID, "video", filename)
|
||||
case "platform":
|
||||
if platform == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "平台参数缺失"})
|
||||
return
|
||||
}
|
||||
filePath = filepath.Join(h.workSvc.WorksDir(), workID, "platform", platform, filename)
|
||||
default:
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "不支持的文件类型"})
|
||||
return
|
||||
}
|
||||
|
||||
_ = os.Remove(filePath)
|
||||
|
||||
modErr := h.workSvc.ModifyWork(workID, func(w *model.WorkConfig) {
|
||||
if w.OriginalNames != nil {
|
||||
delete(w.OriginalNames, filename)
|
||||
}
|
||||
switch fileType {
|
||||
case "image":
|
||||
w.Screenshots = service.RemoveString(w.Screenshots, filename)
|
||||
if w.Cover == filename {
|
||||
if len(w.Screenshots) > 0 {
|
||||
w.Cover = w.Screenshots[0]
|
||||
} else {
|
||||
w.Cover = ""
|
||||
}
|
||||
}
|
||||
case "video":
|
||||
w.VideoFiles = service.RemoveString(w.VideoFiles, filename)
|
||||
case "platform":
|
||||
if w.FileNames != nil {
|
||||
w.FileNames[platform] = service.RemoveString(w.FileNames[platform], filename)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if modErr != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "更新配置失败"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "删除成功"})
|
||||
}
|
||||
72
SproutWorkCollect-Backend-Golang/internal/handler/media.go
Normal file
72
SproutWorkCollect-Backend-Golang/internal/handler/media.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"sproutworkcollect-backend/internal/service"
|
||||
)
|
||||
|
||||
// MediaHandler serves static media files (images, videos, and downloadable assets).
|
||||
type MediaHandler struct {
|
||||
workSvc *service.WorkService
|
||||
rateLimiter *service.RateLimiter
|
||||
}
|
||||
|
||||
// NewMediaHandler wires up a MediaHandler with its dependencies.
|
||||
func NewMediaHandler(workSvc *service.WorkService, rateLimiter *service.RateLimiter) *MediaHandler {
|
||||
return &MediaHandler{workSvc: workSvc, rateLimiter: rateLimiter}
|
||||
}
|
||||
|
||||
// ServeImage handles GET /api/image/:work_id/:filename
|
||||
func (h *MediaHandler) ServeImage(c *gin.Context) {
|
||||
imgPath := filepath.Join(
|
||||
h.workSvc.WorksDir(),
|
||||
c.Param("work_id"),
|
||||
"image",
|
||||
c.Param("filename"),
|
||||
)
|
||||
if _, err := os.Stat(imgPath); os.IsNotExist(err) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "图片不存在"})
|
||||
return
|
||||
}
|
||||
c.File(imgPath)
|
||||
}
|
||||
|
||||
// ServeVideo handles GET /api/video/:work_id/:filename
|
||||
func (h *MediaHandler) ServeVideo(c *gin.Context) {
|
||||
videoPath := filepath.Join(
|
||||
h.workSvc.WorksDir(),
|
||||
c.Param("work_id"),
|
||||
"video",
|
||||
c.Param("filename"),
|
||||
)
|
||||
if _, err := os.Stat(videoPath); os.IsNotExist(err) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "视频不存在"})
|
||||
return
|
||||
}
|
||||
c.File(videoPath)
|
||||
}
|
||||
|
||||
// DownloadFile handles GET /api/download/:work_id/:platform/:filename
|
||||
func (h *MediaHandler) DownloadFile(c *gin.Context) {
|
||||
workID := c.Param("work_id")
|
||||
platform := c.Param("platform")
|
||||
filename := c.Param("filename")
|
||||
|
||||
filePath := filepath.Join(h.workSvc.WorksDir(), workID, "platform", platform, filename)
|
||||
if _, err := os.Stat(filePath); os.IsNotExist(err) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "文件不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
fp := service.Fingerprint(c.ClientIP(), c.GetHeader("User-Agent"))
|
||||
if h.rateLimiter.CanPerform(fp, "download", workID) {
|
||||
_ = h.workSvc.UpdateStats(workID, "download")
|
||||
}
|
||||
|
||||
c.FileAttachment(filePath, filename)
|
||||
}
|
||||
145
SproutWorkCollect-Backend-Golang/internal/handler/public.go
Normal file
145
SproutWorkCollect-Backend-Golang/internal/handler/public.go
Normal file
@@ -0,0 +1,145 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"sproutworkcollect-backend/internal/service"
|
||||
)
|
||||
|
||||
// PublicHandler handles all publicly accessible API endpoints.
|
||||
type PublicHandler struct {
|
||||
workSvc *service.WorkService
|
||||
settingsSvc *service.SettingsService
|
||||
rateLimiter *service.RateLimiter
|
||||
}
|
||||
|
||||
// NewPublicHandler wires up a PublicHandler with its dependencies.
|
||||
func NewPublicHandler(
|
||||
workSvc *service.WorkService,
|
||||
settingsSvc *service.SettingsService,
|
||||
rateLimiter *service.RateLimiter,
|
||||
) *PublicHandler {
|
||||
return &PublicHandler{
|
||||
workSvc: workSvc,
|
||||
settingsSvc: settingsSvc,
|
||||
rateLimiter: rateLimiter,
|
||||
}
|
||||
}
|
||||
|
||||
// GetSettings handles GET /api/settings
|
||||
func (h *PublicHandler) GetSettings(c *gin.Context) {
|
||||
settings, err := h.settingsSvc.Load()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, settings)
|
||||
}
|
||||
|
||||
// GetWorks handles GET /api/works
|
||||
func (h *PublicHandler) GetWorks(c *gin.Context) {
|
||||
works, err := h.workSvc.LoadAllWorks()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responses := make([]any, len(works))
|
||||
for i, w := range works {
|
||||
responses[i] = h.workSvc.BuildResponse(w)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": responses,
|
||||
"total": len(responses),
|
||||
})
|
||||
}
|
||||
|
||||
// GetWorkDetail handles GET /api/works/:work_id
|
||||
func (h *PublicHandler) GetWorkDetail(c *gin.Context) {
|
||||
workID := c.Param("work_id")
|
||||
|
||||
work, err := h.workSvc.LoadWork(workID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"success": false, "message": "作品不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
fp := service.Fingerprint(c.ClientIP(), c.GetHeader("User-Agent"))
|
||||
if h.rateLimiter.CanPerform(fp, "view", workID) {
|
||||
_ = h.workSvc.UpdateStats(workID, "view")
|
||||
// Reload to return the updated view count.
|
||||
if fresh, err2 := h.workSvc.LoadWork(workID); err2 == nil {
|
||||
work = fresh
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": h.workSvc.BuildResponse(work),
|
||||
})
|
||||
}
|
||||
|
||||
// SearchWorks handles GET /api/search?q=...&category=...
|
||||
func (h *PublicHandler) SearchWorks(c *gin.Context) {
|
||||
works, err := h.workSvc.SearchWorks(c.Query("q"), c.Query("category"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responses := make([]any, len(works))
|
||||
for i, w := range works {
|
||||
responses[i] = h.workSvc.BuildResponse(w)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": responses,
|
||||
"total": len(responses),
|
||||
})
|
||||
}
|
||||
|
||||
// GetCategories handles GET /api/categories
|
||||
func (h *PublicHandler) GetCategories(c *gin.Context) {
|
||||
cats, err := h.workSvc.AllCategories()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": cats})
|
||||
}
|
||||
|
||||
// LikeWork handles POST /api/like/:work_id
|
||||
func (h *PublicHandler) LikeWork(c *gin.Context) {
|
||||
workID := c.Param("work_id")
|
||||
|
||||
if _, err := h.workSvc.LoadWork(workID); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"success": false, "message": "作品不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
fp := service.Fingerprint(c.ClientIP(), c.GetHeader("User-Agent"))
|
||||
if !h.rateLimiter.CanPerform(fp, "like", workID) {
|
||||
c.JSON(http.StatusTooManyRequests, gin.H{
|
||||
"success": false,
|
||||
"message": "操作太频繁,请稍后再试",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.workSvc.UpdateStats(workID, "like"); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "点赞失败"})
|
||||
return
|
||||
}
|
||||
|
||||
work, _ := h.workSvc.LoadWork(workID)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "点赞成功",
|
||||
"likes": work.Likes,
|
||||
})
|
||||
}
|
||||
27
SproutWorkCollect-Backend-Golang/internal/middleware/auth.go
Normal file
27
SproutWorkCollect-Backend-Golang/internal/middleware/auth.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// AdminAuth returns a Gin middleware that validates the admin token.
|
||||
// The token may be supplied via the `token` query parameter or the
|
||||
// `Authorization` request header.
|
||||
func AdminAuth(token string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
t := c.Query("token")
|
||||
if t == "" {
|
||||
t = c.GetHeader("Authorization")
|
||||
}
|
||||
if t != token {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
|
||||
"success": false,
|
||||
"message": "权限不足",
|
||||
})
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
16
SproutWorkCollect-Backend-Golang/internal/model/settings.go
Normal file
16
SproutWorkCollect-Backend-Golang/internal/model/settings.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package model
|
||||
|
||||
// Settings represents the site-wide configuration stored in config/settings.json.
|
||||
type Settings struct {
|
||||
SiteName string `json:"网站名字"`
|
||||
SiteDesc string `json:"网站描述"`
|
||||
Author string `json:"站长"`
|
||||
ContactEmail string `json:"联系邮箱"`
|
||||
ThemeColor string `json:"主题颜色"`
|
||||
PageSize int `json:"每页作品数量"`
|
||||
EnableSearch bool `json:"启用搜索"`
|
||||
EnableCategory bool `json:"启用分类"`
|
||||
Icp string `json:"备案号"`
|
||||
Footer string `json:"网站页尾"`
|
||||
Logo string `json:"网站logo"`
|
||||
}
|
||||
75
SproutWorkCollect-Backend-Golang/internal/model/work.go
Normal file
75
SproutWorkCollect-Backend-Golang/internal/model/work.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package model
|
||||
|
||||
// WorkConfig is the data persisted in each work's work_config.json.
|
||||
// JSON field names are kept in Chinese to maintain backward compatibility
|
||||
// with data files written by the original Python backend.
|
||||
type WorkConfig struct {
|
||||
WorkID string `json:"作品ID"`
|
||||
WorkName string `json:"作品作品"`
|
||||
WorkDesc string `json:"作品描述"`
|
||||
Author string `json:"作者"`
|
||||
Version string `json:"作品版本号"`
|
||||
Category string `json:"作品分类"`
|
||||
Tags []string `json:"作品标签"`
|
||||
UploadTime string `json:"上传时间"`
|
||||
UpdateTime string `json:"更新时间"`
|
||||
Platforms []string `json:"支持平台"`
|
||||
FileNames map[string][]string `json:"文件名称"`
|
||||
// 外部下载:每个平台可以配置多个外链下载(带别名)。
|
||||
ExternalDownloads map[string][]ExternalDownload `json:"外部下载,omitempty"`
|
||||
Screenshots []string `json:"作品截图"`
|
||||
VideoFiles []string `json:"作品视频"`
|
||||
Cover string `json:"作品封面"`
|
||||
Downloads int `json:"作品下载量"`
|
||||
Views int `json:"作品浏览量"`
|
||||
Likes int `json:"作品点赞量"`
|
||||
UpdateCount int `json:"作品更新次数"`
|
||||
OriginalNames map[string]string `json:"原始文件名,omitempty"`
|
||||
}
|
||||
|
||||
type ExternalDownload struct {
|
||||
Alias string `json:"别名"`
|
||||
URL string `json:"链接"`
|
||||
}
|
||||
|
||||
// Normalize replaces nil slices/maps with empty equivalents so JSON
|
||||
// serialization produces [] / {} instead of null, matching Python behaviour.
|
||||
func (w *WorkConfig) Normalize() {
|
||||
if w.Tags == nil {
|
||||
w.Tags = []string{}
|
||||
}
|
||||
if w.Platforms == nil {
|
||||
w.Platforms = []string{}
|
||||
}
|
||||
if w.FileNames == nil {
|
||||
w.FileNames = map[string][]string{}
|
||||
}
|
||||
if w.ExternalDownloads == nil {
|
||||
w.ExternalDownloads = map[string][]ExternalDownload{}
|
||||
}
|
||||
if w.Screenshots == nil {
|
||||
w.Screenshots = []string{}
|
||||
}
|
||||
if w.VideoFiles == nil {
|
||||
w.VideoFiles = []string{}
|
||||
}
|
||||
}
|
||||
|
||||
// WorkResponse is a WorkConfig with dynamically computed link fields appended.
|
||||
// These link fields are NEVER stored in work_config.json; they are built on
|
||||
// the fly at response time.
|
||||
type WorkResponse struct {
|
||||
WorkConfig
|
||||
// 下载链接 is always present (empty map when there are no download files).
|
||||
DownloadLinks map[string][]string `json:"下载链接"`
|
||||
// 下载资源:统一返回“本地下载 + 外部下载”,前端可直接按别名渲染按钮/链接。
|
||||
DownloadResources map[string][]DownloadResource `json:"下载资源"`
|
||||
ImageLinks []string `json:"图片链接,omitempty"`
|
||||
VideoLinks []string `json:"视频链接,omitempty"`
|
||||
}
|
||||
|
||||
type DownloadResource struct {
|
||||
Type string `json:"类型"` // local | external
|
||||
Alias string `json:"别名"`
|
||||
URL string `json:"链接"`
|
||||
}
|
||||
81
SproutWorkCollect-Backend-Golang/internal/router/router.go
Normal file
81
SproutWorkCollect-Backend-Golang/internal/router/router.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"sproutworkcollect-backend/internal/config"
|
||||
"sproutworkcollect-backend/internal/handler"
|
||||
"sproutworkcollect-backend/internal/middleware"
|
||||
"sproutworkcollect-backend/internal/service"
|
||||
)
|
||||
|
||||
// Setup creates and configures the Gin engine: middleware, services, handlers, and routes.
|
||||
func Setup(cfg *config.Config) *gin.Engine {
|
||||
if !cfg.Debug {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
}
|
||||
|
||||
r := gin.Default()
|
||||
|
||||
// Allow files up to 32 MB to stay in memory; larger ones spill to temp disk files.
|
||||
// This keeps RAM usage bounded even for gigabyte-scale uploads.
|
||||
r.MaxMultipartMemory = 32 << 20
|
||||
|
||||
// 允许所有来源,并显式放开 Authorization 头,解决跨域访问后台接口时的预检失败问题。
|
||||
corsCfg := cors.Config{
|
||||
AllowOrigins: []string{"*"},
|
||||
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
||||
AllowHeaders: []string{
|
||||
"Origin",
|
||||
"Content-Type",
|
||||
"Accept",
|
||||
"Authorization",
|
||||
"X-Requested-With",
|
||||
},
|
||||
ExposeHeaders: []string{"Content-Length"},
|
||||
AllowCredentials: false,
|
||||
MaxAge: 12 * time.Hour,
|
||||
}
|
||||
r.Use(cors.New(corsCfg))
|
||||
|
||||
// ─── Services ─────────────────────────────────────────────────────────────
|
||||
workSvc := service.NewWorkService(cfg)
|
||||
settingsSvc := service.NewSettingsService(cfg)
|
||||
rateLimiter := service.NewRateLimiter()
|
||||
|
||||
// ─── Handlers ─────────────────────────────────────────────────────────────
|
||||
pub := handler.NewPublicHandler(workSvc, settingsSvc, rateLimiter)
|
||||
media := handler.NewMediaHandler(workSvc, rateLimiter)
|
||||
admin := handler.NewAdminHandler(workSvc)
|
||||
|
||||
// ─── Public routes ────────────────────────────────────────────────────────
|
||||
api := r.Group("/api")
|
||||
{
|
||||
api.GET("/settings", pub.GetSettings)
|
||||
api.GET("/works", pub.GetWorks)
|
||||
api.GET("/works/:work_id", pub.GetWorkDetail)
|
||||
api.GET("/search", pub.SearchWorks)
|
||||
api.GET("/categories", pub.GetCategories)
|
||||
api.POST("/like/:work_id", pub.LikeWork)
|
||||
|
||||
api.GET("/image/:work_id/:filename", media.ServeImage)
|
||||
api.GET("/video/:work_id/:filename", media.ServeVideo)
|
||||
api.GET("/download/:work_id/:platform/:filename", media.DownloadFile)
|
||||
}
|
||||
|
||||
// ─── Admin routes (token-protected) ──────────────────────────────────────
|
||||
adm := api.Group("/admin", middleware.AdminAuth(cfg.AdminToken))
|
||||
{
|
||||
adm.GET("/works", admin.GetWorks)
|
||||
adm.POST("/works", admin.CreateWork)
|
||||
adm.PUT("/works/:work_id", admin.UpdateWork)
|
||||
adm.DELETE("/works/:work_id", admin.DeleteWork)
|
||||
adm.POST("/upload/:work_id/:file_type", admin.UploadFile)
|
||||
adm.DELETE("/delete-file/:work_id/:file_type/:filename", admin.DeleteFile)
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// rateLimits defines minimum seconds between the same action by the same user on the same work.
|
||||
var rateLimits = map[string]int64{
|
||||
"view": 60,
|
||||
"download": 300,
|
||||
"like": 3600,
|
||||
}
|
||||
|
||||
// RateLimiter provides per-user, per-action, per-work rate limiting backed by an in-memory store.
|
||||
// The store is never persisted; it resets on service restart (same behaviour as the Python version).
|
||||
type RateLimiter struct {
|
||||
mu sync.Mutex
|
||||
// fingerprint → actionType → workID → last unix timestamp
|
||||
actions map[string]map[string]map[string]int64
|
||||
}
|
||||
|
||||
// NewRateLimiter allocates a new empty RateLimiter.
|
||||
func NewRateLimiter() *RateLimiter {
|
||||
return &RateLimiter{
|
||||
actions: make(map[string]map[string]map[string]int64),
|
||||
}
|
||||
}
|
||||
|
||||
// CanPerform returns true and records the timestamp if the rate limit window has elapsed.
|
||||
// Returns false if the action is too frequent.
|
||||
func (rl *RateLimiter) CanPerform(fingerprint, actionType, workID string) bool {
|
||||
rl.mu.Lock()
|
||||
defer rl.mu.Unlock()
|
||||
|
||||
limit, ok := rateLimits[actionType]
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
|
||||
if rl.actions[fingerprint] == nil {
|
||||
rl.actions[fingerprint] = make(map[string]map[string]int64)
|
||||
}
|
||||
if rl.actions[fingerprint][actionType] == nil {
|
||||
rl.actions[fingerprint][actionType] = make(map[string]int64)
|
||||
}
|
||||
|
||||
last := rl.actions[fingerprint][actionType][workID]
|
||||
if now-last >= limit {
|
||||
rl.actions[fingerprint][actionType][workID] = now
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Fingerprint creates an MD5 hex string from IP and User-Agent for rate-limit keying.
|
||||
func Fingerprint(ip, userAgent string) string {
|
||||
h := md5.Sum([]byte(ip + ":" + userAgent))
|
||||
return fmt.Sprintf("%x", h)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"sproutworkcollect-backend/internal/config"
|
||||
"sproutworkcollect-backend/internal/model"
|
||||
)
|
||||
|
||||
var defaultSettings = model.Settings{
|
||||
SiteName: "✨ 萌芽作品集 ✨",
|
||||
SiteDesc: "🎨 展示个人制作的一些小创意和小项目,欢迎交流讨论 💬",
|
||||
Author: "👨💻 by-树萌芽",
|
||||
ContactEmail: "3205788256@qq.com",
|
||||
ThemeColor: "#81c784",
|
||||
PageSize: 6,
|
||||
EnableSearch: true,
|
||||
EnableCategory: true,
|
||||
Icp: "📄 蜀ICP备2025151694号",
|
||||
Footer: "✨ 萌芽作品集 ✨ | Copyright © 2025-2025 smy ",
|
||||
Logo: "assets/logo.png",
|
||||
}
|
||||
|
||||
// SettingsService manages the site-wide settings file.
|
||||
type SettingsService struct {
|
||||
cfg *config.Config
|
||||
}
|
||||
|
||||
// NewSettingsService creates a SettingsService with the given config.
|
||||
func NewSettingsService(cfg *config.Config) *SettingsService {
|
||||
return &SettingsService{cfg: cfg}
|
||||
}
|
||||
|
||||
// Load reads settings.json, returning built-in defaults when the file is absent or malformed.
|
||||
func (s *SettingsService) Load() (*model.Settings, error) {
|
||||
path := filepath.Join(s.cfg.ConfigDir, "settings.json")
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
d := defaultSettings
|
||||
return &d, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
var settings model.Settings
|
||||
if err := json.Unmarshal(data, &settings); err != nil {
|
||||
d := defaultSettings
|
||||
return &d, nil
|
||||
}
|
||||
return &settings, nil
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"sproutworkcollect-backend/internal/config"
|
||||
"sproutworkcollect-backend/internal/model"
|
||||
)
|
||||
|
||||
// WorkService manages all work data operations with concurrent-safe file I/O.
|
||||
type WorkService struct {
|
||||
cfg *config.Config
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewWorkService creates a WorkService with the given config.
|
||||
func NewWorkService(cfg *config.Config) *WorkService {
|
||||
return &WorkService{cfg: cfg}
|
||||
}
|
||||
|
||||
// WorksDir returns the configured works root directory.
|
||||
func (s *WorkService) WorksDir() string { return s.cfg.WorksDir }
|
||||
|
||||
// WorkExists reports whether a work directory is present on disk.
|
||||
func (s *WorkService) WorkExists(workID string) bool {
|
||||
_, err := os.Stat(filepath.Join(s.cfg.WorksDir, workID))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// ─── Read operations ──────────────────────────────────────────────────────────
|
||||
|
||||
// LoadWork loads and returns a single work config from disk (read-locked).
|
||||
func (s *WorkService) LoadWork(workID string) (*model.WorkConfig, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.loadWork(workID)
|
||||
}
|
||||
|
||||
// loadWork is the internal (unlocked) loader; callers must hold at least an RLock.
|
||||
func (s *WorkService) loadWork(workID string) (*model.WorkConfig, error) {
|
||||
path := filepath.Join(s.cfg.WorksDir, workID, "work_config.json")
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var work model.WorkConfig
|
||||
if err := json.Unmarshal(data, &work); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
work.Normalize()
|
||||
return &work, nil
|
||||
}
|
||||
|
||||
// LoadAllWorks loads every work and returns them sorted by UpdateTime descending.
|
||||
func (s *WorkService) LoadAllWorks() ([]*model.WorkConfig, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
entries, err := os.ReadDir(s.cfg.WorksDir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return []*model.WorkConfig{}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var works []*model.WorkConfig
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() {
|
||||
continue
|
||||
}
|
||||
w, err := s.loadWork(e.Name())
|
||||
if err != nil {
|
||||
continue // skip broken configs
|
||||
}
|
||||
works = append(works, w)
|
||||
}
|
||||
|
||||
sort.Slice(works, func(i, j int) bool {
|
||||
return works[i].UpdateTime > works[j].UpdateTime
|
||||
})
|
||||
return works, nil
|
||||
}
|
||||
|
||||
// SearchWorks filters all works by keyword (name / desc / tags) and/or category.
|
||||
func (s *WorkService) SearchWorks(query, category string) ([]*model.WorkConfig, error) {
|
||||
all, err := s.LoadAllWorks()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
q := strings.ToLower(query)
|
||||
var result []*model.WorkConfig
|
||||
for _, w := range all {
|
||||
if q != "" {
|
||||
matched := strings.Contains(strings.ToLower(w.WorkName), q) ||
|
||||
strings.Contains(strings.ToLower(w.WorkDesc), q)
|
||||
if !matched {
|
||||
for _, tag := range w.Tags {
|
||||
if strings.Contains(strings.ToLower(tag), q) {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if category != "" && w.Category != category {
|
||||
continue
|
||||
}
|
||||
result = append(result, w)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// AllCategories returns a deduplicated list of all work categories.
|
||||
func (s *WorkService) AllCategories() ([]string, error) {
|
||||
all, err := s.LoadAllWorks()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seen := make(map[string]struct{})
|
||||
var cats []string
|
||||
for _, w := range all {
|
||||
if w.Category != "" {
|
||||
if _, ok := seen[w.Category]; !ok {
|
||||
seen[w.Category] = struct{}{}
|
||||
cats = append(cats, w.Category)
|
||||
}
|
||||
}
|
||||
}
|
||||
if cats == nil {
|
||||
cats = []string{}
|
||||
}
|
||||
return cats, nil
|
||||
}
|
||||
|
||||
// BuildResponse attaches dynamically computed link fields to a work for API responses.
|
||||
// These fields are never written back to disk.
|
||||
func (s *WorkService) BuildResponse(w *model.WorkConfig) *model.WorkResponse {
|
||||
resp := &model.WorkResponse{
|
||||
WorkConfig: *w,
|
||||
DownloadLinks: make(map[string][]string),
|
||||
DownloadResources: make(map[string][]model.DownloadResource),
|
||||
}
|
||||
|
||||
for _, platform := range w.Platforms {
|
||||
if files, ok := w.FileNames[platform]; ok && len(files) > 0 {
|
||||
links := make([]string, len(files))
|
||||
for i, f := range files {
|
||||
rel := fmt.Sprintf("/api/download/%s/%s/%s", w.WorkID, platform, f)
|
||||
links[i] = rel
|
||||
resp.DownloadResources[platform] = append(resp.DownloadResources[platform], model.DownloadResource{
|
||||
Type: "local",
|
||||
Alias: f,
|
||||
URL: rel,
|
||||
})
|
||||
}
|
||||
resp.DownloadLinks[platform] = links
|
||||
}
|
||||
|
||||
// 外部下载链接(带别名)
|
||||
if extList, ok := w.ExternalDownloads[platform]; ok && len(extList) > 0 {
|
||||
for _, item := range extList {
|
||||
if strings.TrimSpace(item.URL) == "" {
|
||||
continue
|
||||
}
|
||||
alias := strings.TrimSpace(item.Alias)
|
||||
if alias == "" {
|
||||
alias = "外部下载"
|
||||
}
|
||||
resp.DownloadResources[platform] = append(resp.DownloadResources[platform], model.DownloadResource{
|
||||
Type: "external",
|
||||
Alias: alias,
|
||||
URL: strings.TrimSpace(item.URL),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(w.Screenshots) > 0 {
|
||||
resp.ImageLinks = make([]string, len(w.Screenshots))
|
||||
for i, img := range w.Screenshots {
|
||||
resp.ImageLinks[i] = fmt.Sprintf("/api/image/%s/%s", w.WorkID, img)
|
||||
}
|
||||
}
|
||||
|
||||
if len(w.VideoFiles) > 0 {
|
||||
resp.VideoLinks = make([]string, len(w.VideoFiles))
|
||||
for i, vid := range w.VideoFiles {
|
||||
resp.VideoLinks[i] = fmt.Sprintf("/api/video/%s/%s", w.WorkID, vid)
|
||||
}
|
||||
}
|
||||
|
||||
return resp
|
||||
}
|
||||
|
||||
// ─── Write operations ─────────────────────────────────────────────────────────
|
||||
|
||||
// SaveWork atomically persists a work config (write-locked).
|
||||
// It writes to a .tmp file first, then renames to guarantee atomicity.
|
||||
func (s *WorkService) SaveWork(work *model.WorkConfig) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.saveWork(work)
|
||||
}
|
||||
|
||||
// saveWork is the internal (unlocked) writer; callers must hold the write lock.
|
||||
func (s *WorkService) saveWork(work *model.WorkConfig) error {
|
||||
configPath := filepath.Join(s.cfg.WorksDir, work.WorkID, "work_config.json")
|
||||
data, err := json.MarshalIndent(work, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("序列化配置失败: %w", err)
|
||||
}
|
||||
tmp := configPath + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, 0644); err != nil {
|
||||
return fmt.Errorf("写入临时文件失败: %w", err)
|
||||
}
|
||||
if err := os.Rename(tmp, configPath); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return fmt.Errorf("原子写入失败: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ModifyWork loads a work under a write lock, applies fn, then saves the result.
|
||||
// Using this helper avoids the load–modify–save TOCTOU race for concurrent requests.
|
||||
func (s *WorkService) ModifyWork(workID string, fn func(*model.WorkConfig)) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
work, err := s.loadWork(workID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fn(work)
|
||||
work.UpdateTime = now()
|
||||
return s.saveWork(work)
|
||||
}
|
||||
|
||||
// UpdateStats increments a statistical counter ("view" | "download" | "like").
|
||||
func (s *WorkService) UpdateStats(workID, statType string) error {
|
||||
return s.ModifyWork(workID, func(w *model.WorkConfig) {
|
||||
switch statType {
|
||||
case "view":
|
||||
w.Views++
|
||||
case "download":
|
||||
w.Downloads++
|
||||
case "like":
|
||||
w.Likes++
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// CreateWork initialises a new work directory tree and writes the first config.
|
||||
func (s *WorkService) CreateWork(work *model.WorkConfig) error {
|
||||
workDir := filepath.Join(s.cfg.WorksDir, work.WorkID)
|
||||
if _, err := os.Stat(workDir); err == nil {
|
||||
return fmt.Errorf("作品ID已存在")
|
||||
}
|
||||
|
||||
dirs := []string{
|
||||
workDir,
|
||||
filepath.Join(workDir, "image"),
|
||||
filepath.Join(workDir, "video"),
|
||||
filepath.Join(workDir, "platform"),
|
||||
}
|
||||
for _, p := range work.Platforms {
|
||||
dirs = append(dirs, filepath.Join(workDir, "platform", p))
|
||||
}
|
||||
for _, d := range dirs {
|
||||
if err := os.MkdirAll(d, 0755); err != nil {
|
||||
return fmt.Errorf("创建目录失败 %s: %w", d, err)
|
||||
}
|
||||
}
|
||||
return s.SaveWork(work)
|
||||
}
|
||||
|
||||
// UpdateWork merges incoming data into the existing config, preserving statistics
|
||||
// when the caller does not provide them (zero values).
|
||||
func (s *WorkService) UpdateWork(workID string, incoming *model.WorkConfig) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
existing, err := s.loadWork(workID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("作品不存在: %w", err)
|
||||
}
|
||||
|
||||
// 兼容旧前端:如果某些字段未带上,则保留旧值,避免被清空。
|
||||
if incoming.FileNames == nil {
|
||||
incoming.FileNames = existing.FileNames
|
||||
}
|
||||
if incoming.ExternalDownloads == nil {
|
||||
incoming.ExternalDownloads = existing.ExternalDownloads
|
||||
}
|
||||
if incoming.Screenshots == nil {
|
||||
incoming.Screenshots = existing.Screenshots
|
||||
}
|
||||
if incoming.VideoFiles == nil {
|
||||
incoming.VideoFiles = existing.VideoFiles
|
||||
}
|
||||
if incoming.Cover == "" {
|
||||
incoming.Cover = existing.Cover
|
||||
}
|
||||
if incoming.OriginalNames == nil {
|
||||
incoming.OriginalNames = existing.OriginalNames
|
||||
}
|
||||
|
||||
if incoming.Downloads == 0 {
|
||||
incoming.Downloads = existing.Downloads
|
||||
}
|
||||
if incoming.Views == 0 {
|
||||
incoming.Views = existing.Views
|
||||
}
|
||||
if incoming.Likes == 0 {
|
||||
incoming.Likes = existing.Likes
|
||||
}
|
||||
if incoming.UploadTime == "" {
|
||||
incoming.UploadTime = existing.UploadTime
|
||||
}
|
||||
|
||||
incoming.WorkID = workID
|
||||
incoming.UpdateTime = now()
|
||||
incoming.UpdateCount = existing.UpdateCount + 1
|
||||
incoming.Normalize()
|
||||
|
||||
return s.saveWork(incoming)
|
||||
}
|
||||
|
||||
// DeleteWork removes the entire work directory.
|
||||
func (s *WorkService) DeleteWork(workID string) error {
|
||||
workDir := filepath.Join(s.cfg.WorksDir, workID)
|
||||
if _, err := os.Stat(workDir); os.IsNotExist(err) {
|
||||
return fmt.Errorf("作品不存在")
|
||||
}
|
||||
return os.RemoveAll(workDir)
|
||||
}
|
||||
|
||||
// ─── Utility helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
// SafeFilename sanitises a filename while preserving CJK (Chinese) characters.
|
||||
func SafeFilename(filename string) string {
|
||||
if filename == "" {
|
||||
return "unnamed_file"
|
||||
}
|
||||
var sb strings.Builder
|
||||
for _, r := range filename {
|
||||
switch {
|
||||
case r >= 0x4E00 && r <= 0x9FFF: // CJK Unified Ideographs
|
||||
sb.WriteRune(r)
|
||||
case unicode.IsLetter(r) || unicode.IsDigit(r):
|
||||
sb.WriteRune(r)
|
||||
case r == '-' || r == '_' || r == '.' || r == ' ':
|
||||
sb.WriteRune(r)
|
||||
}
|
||||
}
|
||||
safe := strings.ReplaceAll(sb.String(), " ", "_")
|
||||
safe = strings.Trim(safe, "._")
|
||||
if safe == "" {
|
||||
return "unnamed_file"
|
||||
}
|
||||
return safe
|
||||
}
|
||||
|
||||
// UniqueFilename returns a filename that does not appear in existing.
|
||||
// If base already conflicts, it appends _1, _2, … until unique.
|
||||
func UniqueFilename(base string, existing []string) string {
|
||||
set := make(map[string]bool, len(existing))
|
||||
for _, f := range existing {
|
||||
set[f] = true
|
||||
}
|
||||
if !set[base] {
|
||||
return base
|
||||
}
|
||||
ext := filepath.Ext(base)
|
||||
stem := strings.TrimSuffix(base, ext)
|
||||
for i := 1; ; i++ {
|
||||
name := fmt.Sprintf("%s_%d%s", stem, i, ext)
|
||||
if !set[name] {
|
||||
return name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ContainsString reports whether slice s contains value v.
|
||||
func ContainsString(s []string, v string) bool {
|
||||
for _, item := range s {
|
||||
if item == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// RemoveString returns a copy of s with the first occurrence of v removed.
|
||||
func RemoveString(s []string, v string) []string {
|
||||
out := make([]string, 0, len(s))
|
||||
for _, item := range s {
|
||||
if item != v {
|
||||
out = append(out, item)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// now returns the current local time in Python-compatible ISO8601 format.
|
||||
func now() string {
|
||||
return time.Now().Format("2006-01-02T15:04:05.000000")
|
||||
}
|
||||
24
SproutWorkCollect-Backend-Golang/main.go
Normal file
24
SproutWorkCollect-Backend-Golang/main.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"sproutworkcollect-backend/internal/config"
|
||||
"sproutworkcollect-backend/internal/router"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg := config.Load()
|
||||
|
||||
r := router.Setup(cfg)
|
||||
|
||||
addr := fmt.Sprintf("0.0.0.0:%d", cfg.Port)
|
||||
log.Printf("[SproutWorkCollect] 服务启动 → http://%s", addr)
|
||||
log.Printf("[SproutWorkCollect] WorksDir : %s", cfg.WorksDir)
|
||||
log.Printf("[SproutWorkCollect] ConfigDir : %s", cfg.ConfigDir)
|
||||
|
||||
if err := r.Run(addr); err != nil {
|
||||
log.Fatalf("服务启动失败: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user