Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c163f2b741 | ||
|
|
08140d7c6b | ||
|
|
44d0bfc217 | ||
|
|
17eb6c134e | ||
|
|
8779f0fe81 | ||
|
|
04112c4fd2 | ||
|
|
3172928306 | ||
|
|
62bc2c6fda | ||
|
|
007fc7b938 | ||
|
|
3aaa7b1d0c | ||
|
|
31e1a8977b |
@@ -3,8 +3,6 @@
|
||||
POSTGRES_USER=opengoods
|
||||
POSTGRES_PASSWORD=change-me
|
||||
POSTGRES_DB=opengoods
|
||||
MINIO_ROOT_USER=opengoods
|
||||
MINIO_ROOT_PASSWORD=change-me
|
||||
|
||||
# Empty uses loopback and private-network defaults; use "none" to trust no proxies.
|
||||
OPENGOODS_TRUSTED_PROXIES=
|
||||
|
||||
@@ -1,2 +1,108 @@
|
||||
# goods
|
||||
商品档案公开API
|
||||
# OpenGoods
|
||||
|
||||
OpenGoods(天工·商品标签)提供公开、只读的商品事实 API,并配套运营后台和数据采集工具。项目整理商品名称、品牌、品类、条码、配料、营养成分、产地等客观信息,不提供购买或交易功能。
|
||||
|
||||
## 项目组成
|
||||
|
||||
- **公开 API**:Go 服务,提供商品搜索、品牌和商品详情等只读接口。
|
||||
- **运营后台**:独立的 Go 管理服务,提供登录、商品维护、投稿审核、API Key 和导入功能。
|
||||
- **数据采集**:`ingestion/` 是 Python 采集与 ETL 包;`tools/bypos-collector/` 包含 BYPOS 采集工具。
|
||||
- **前端**:`public-frontend/` 是公开站点,`admin-frontend/` 是运营后台界面;两者均使用 React、Vite 和 TypeScript。
|
||||
- **数据库迁移**:`migrations/` 保存 PostgreSQL schema 的正向与回滚迁移。
|
||||
|
||||
## API 与文档
|
||||
|
||||
- API 使用说明:[`docs/api.md`](docs/api.md)
|
||||
- OpenAPI 规范源文件:[`api/internal/handler/openapi.json`](api/internal/handler/openapi.json)
|
||||
- 数据契约:[`docs/data-contract.md`](docs/data-contract.md)
|
||||
- 采集说明:[`docs/etl-openfoodfacts.md`](docs/etl-openfoodfacts.md) 和 [`docs/ingestion-management.md`](docs/ingestion-management.md)
|
||||
- 部署指南:[`docs/deploy.md`](docs/deploy.md)
|
||||
|
||||
运行中的公开服务也通过 `GET /api/v1/openapi.json` 提供机器可读规范。
|
||||
|
||||
## 本地开发
|
||||
|
||||
需要 Go(版本要求见 `api/go.mod`)、Docker Compose、Node.js/npm,以及 Python 3.11 或更新版本(用于采集侧开发)。
|
||||
|
||||
启动 PostgreSQL 和 Redis:
|
||||
|
||||
```bash
|
||||
docker compose up -d postgres redis
|
||||
```
|
||||
|
||||
安装迁移工具并应用数据库迁移:
|
||||
|
||||
```bash
|
||||
go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@v4.18.1
|
||||
migrate -path migrations \
|
||||
-database 'postgres://opengoods:opengoods@localhost:5432/opengoods?sslmode=disable' up
|
||||
```
|
||||
|
||||
启动公开 API:
|
||||
|
||||
```bash
|
||||
cd api
|
||||
export OPENGOODS_DATABASE_URL='postgres://opengoods:opengoods@localhost:5432/opengoods?sslmode=disable'
|
||||
export OPENGOODS_REDIS_URL='redis://localhost:6379/0'
|
||||
go run ./cmd/server
|
||||
```
|
||||
|
||||
在另一个终端启动运营后台(本地示例凭据请自行替换):
|
||||
|
||||
```bash
|
||||
cd api
|
||||
export OPENGOODS_DATABASE_URL='postgres://opengoods:opengoods@localhost:5432/opengoods?sslmode=disable'
|
||||
export OPENGOODS_REDIS_URL='redis://localhost:6379/0'
|
||||
export GOODS_ADMIN_ADDR=':8081'
|
||||
export GOODS_ADMIN_USER='admin'
|
||||
export GOODS_ADMIN_PASSWORD='local-development-password'
|
||||
export GOODS_ADMIN_JWT_SECRET='local-development-secret-change-before-use'
|
||||
go run ./cmd/admin
|
||||
```
|
||||
|
||||
前端可在各自目录启动 Vite 开发服务器(分别在两个终端运行):
|
||||
|
||||
```bash
|
||||
cd public-frontend
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
```bash
|
||||
cd admin-frontend
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## 测试与构建
|
||||
|
||||
Go API:
|
||||
|
||||
```bash
|
||||
cd api
|
||||
test -z "$(gofmt -l .)"
|
||||
go vet ./...
|
||||
go build ./...
|
||||
go test ./...
|
||||
```
|
||||
|
||||
Python 采集侧:
|
||||
|
||||
```bash
|
||||
cd ingestion
|
||||
pip install -e ".[dev]"
|
||||
ruff check .
|
||||
ruff format --check .
|
||||
pytest -q
|
||||
```
|
||||
|
||||
前端构建:
|
||||
|
||||
```bash
|
||||
(cd public-frontend && npm install && npm run build)
|
||||
(cd admin-frontend && npm install && npm run build)
|
||||
```
|
||||
|
||||
生产部署步骤、环境变量和反向代理配置见[部署文档](docs/deploy.md)。
|
||||
|
||||
可信代理通过 `OPENGOODS_TRUSTED_PROXIES` 配置;支持格式与默认行为见部署指南。
|
||||
|
||||
+33
-6
@@ -8,7 +8,9 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
@@ -51,6 +53,8 @@ func main() {
|
||||
if err != nil {
|
||||
log.Fatalf("invalid OPENGOODS_TRUSTED_PROXIES: %v", err)
|
||||
}
|
||||
runCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
// Password: prefer a bcrypt hash; otherwise hash a plaintext password.
|
||||
var passwordHash []byte
|
||||
@@ -75,14 +79,12 @@ func main() {
|
||||
log.Print("warning: GOODS_ADMIN_JWT_SECRET not set; using a random secret (tokens invalidate on restart)")
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, dbURL)
|
||||
pool, err := pgxpool.New(context.Background(), dbURL)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to create db pool: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
pingCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
log.Printf("warning: database not reachable at startup: %v", err)
|
||||
@@ -102,9 +104,34 @@ func main() {
|
||||
Addr: addr,
|
||||
Handler: h.Router(),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 60 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
log.Printf("OpenGoods admin console listening on %s (base path %s)", addr, basePath)
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf("server error: %v", err)
|
||||
serverErr := make(chan error, 1)
|
||||
go func() {
|
||||
serverErr <- srv.ListenAndServe()
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-serverErr:
|
||||
pool.Close()
|
||||
if err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf("server error: %v", err)
|
||||
}
|
||||
case <-runCtx.Done():
|
||||
log.Print("shutdown signal received")
|
||||
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 25*time.Second)
|
||||
err := srv.Shutdown(shutdownCtx)
|
||||
shutdownCancel()
|
||||
if err != nil {
|
||||
log.Printf("server shutdown: %v", err)
|
||||
}
|
||||
pool.Close()
|
||||
if err := <-serverErr; err != nil && err != http.ErrServerClosed {
|
||||
log.Printf("server error after shutdown: %v", err)
|
||||
}
|
||||
log.Print("OpenGoods admin console shutdown complete")
|
||||
}
|
||||
}
|
||||
|
||||
+34
-6
@@ -5,6 +5,9 @@ import (
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
@@ -24,15 +27,15 @@ func main() {
|
||||
if err != nil {
|
||||
log.Fatalf("invalid OPENGOODS_TRUSTED_PROXIES: %v", err)
|
||||
}
|
||||
runCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, cfg.DatabaseURL)
|
||||
pool, err := pgxpool.New(context.Background(), cfg.DatabaseURL)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to create db pool: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
pingCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
log.Printf("warning: database not reachable at startup: %v", err)
|
||||
@@ -56,10 +59,35 @@ func main() {
|
||||
Addr: cfg.Addr,
|
||||
Handler: h.Router(),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 60 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
|
||||
log.Printf("OpenGoods API listening on %s", cfg.Addr)
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf("server error: %v", err)
|
||||
serverErr := make(chan error, 1)
|
||||
go func() {
|
||||
serverErr <- srv.ListenAndServe()
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-serverErr:
|
||||
pool.Close()
|
||||
if err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf("server error: %v", err)
|
||||
}
|
||||
case <-runCtx.Done():
|
||||
log.Print("shutdown signal received")
|
||||
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 25*time.Second)
|
||||
err := srv.Shutdown(shutdownCtx)
|
||||
shutdownCancel()
|
||||
if err != nil {
|
||||
log.Printf("server shutdown: %v", err)
|
||||
}
|
||||
pool.Close()
|
||||
if err := <-serverErr; err != nil && err != http.ErrServerClosed {
|
||||
log.Printf("server error after shutdown: %v", err)
|
||||
}
|
||||
log.Print("OpenGoods API shutdown complete")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,10 +8,11 @@ import (
|
||||
// rateLimiter is a simple fixed-window per-key limiter used to throttle
|
||||
// anonymous public submissions (basic anti-spam; captcha can be added later).
|
||||
type rateLimiter struct {
|
||||
mu sync.Mutex
|
||||
hits map[string][]time.Time
|
||||
limit int
|
||||
window time.Duration
|
||||
mu sync.Mutex
|
||||
hits map[string][]time.Time
|
||||
limit int
|
||||
window time.Duration
|
||||
lastPrune time.Time
|
||||
}
|
||||
|
||||
func newRateLimiter(limit int, window time.Duration) *rateLimiter {
|
||||
@@ -26,12 +27,19 @@ func (r *rateLimiter) allow(key string) bool {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
kept := r.hits[key][:0]
|
||||
for _, t := range r.hits[key] {
|
||||
if t.After(cutoff) {
|
||||
kept = append(kept, t)
|
||||
if now.Sub(r.lastPrune) > r.window {
|
||||
for expiredKey, hits := range r.hits {
|
||||
kept := pruneRateLimitHits(hits, cutoff)
|
||||
if len(kept) == 0 {
|
||||
delete(r.hits, expiredKey)
|
||||
} else {
|
||||
r.hits[expiredKey] = kept
|
||||
}
|
||||
}
|
||||
r.lastPrune = now
|
||||
}
|
||||
|
||||
kept := pruneRateLimitHits(r.hits[key], cutoff)
|
||||
if len(kept) >= r.limit {
|
||||
r.hits[key] = kept
|
||||
return false
|
||||
@@ -39,3 +47,13 @@ func (r *rateLimiter) allow(key string) bool {
|
||||
r.hits[key] = append(kept, now)
|
||||
return true
|
||||
}
|
||||
|
||||
func pruneRateLimitHits(hits []time.Time, cutoff time.Time) []time.Time {
|
||||
kept := hits[:0]
|
||||
for _, hit := range hits {
|
||||
if hit.After(cutoff) {
|
||||
kept = append(kept, hit)
|
||||
}
|
||||
}
|
||||
return kept
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package adminhandler
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRateLimiterPrunesExpiredKeysAndPreservesLiveLimits(t *testing.T) {
|
||||
window := time.Minute
|
||||
now := time.Now()
|
||||
limiter := newRateLimiter(2, window)
|
||||
limiter.hits["expired"] = []time.Time{now.Add(-2 * window)}
|
||||
limiter.hits["live"] = []time.Time{now.Add(-time.Second)}
|
||||
limiter.lastPrune = now.Add(-2 * window)
|
||||
|
||||
if !limiter.allow("live") {
|
||||
t.Fatal("allow rejected a live key below its limit")
|
||||
}
|
||||
if _, ok := limiter.hits["expired"]; ok {
|
||||
t.Fatal("expired key was not pruned")
|
||||
}
|
||||
if got := len(limiter.hits["live"]); got != 2 {
|
||||
t.Fatalf("live key hit count = %d, want 2", got)
|
||||
}
|
||||
if limiter.allow("live") {
|
||||
t.Fatal("allow accepted a live key at its limit")
|
||||
}
|
||||
if got := len(limiter.hits["live"]); got != 2 {
|
||||
t.Fatalf("live key hit count after rejection = %d, want 2", got)
|
||||
}
|
||||
}
|
||||
+2
-16
@@ -24,26 +24,12 @@ services:
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
|
||||
minio:
|
||||
image: minio/minio:latest
|
||||
restart: unless-stopped
|
||||
command: server /data --console-address ":9001"
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD}
|
||||
volumes:
|
||||
- miniodata:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "mc", "ready", "local"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: api/Dockerfile.prod
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 30s
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -61,6 +47,7 @@ services:
|
||||
context: .
|
||||
dockerfile: api/Dockerfile.admin
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 30s
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -76,4 +63,3 @@ services:
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
miniodata:
|
||||
|
||||
@@ -25,23 +25,6 @@ services:
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
minio:
|
||||
image: minio/minio:latest
|
||||
command: server /data --console-address ":9001"
|
||||
environment:
|
||||
MINIO_ROOT_USER: opengoods
|
||||
MINIO_ROOT_PASSWORD: opengoods123
|
||||
ports:
|
||||
- "9000:9000"
|
||||
- "9001:9001"
|
||||
volumes:
|
||||
- miniodata:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "mc", "ready", "local"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
api:
|
||||
build: ./api
|
||||
depends_on:
|
||||
@@ -58,4 +41,3 @@ services:
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
miniodata:
|
||||
|
||||
@@ -33,4 +33,4 @@
|
||||
- 对外 API 在 `sources` 中透明返回来源与其许可。
|
||||
|
||||
## 6. 版本
|
||||
- 本契约随 schema 演进版本化;任何 schema 变更需同步更新:迁移(SQL) + 本契约 + `docs/openapi.yaml`。
|
||||
- 本契约随 schema 演进版本化;任何 schema 变更需同步更新:迁移(SQL) + 本契约 + `api/internal/handler/openapi.json`。
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
用 `docker-compose.prod.yml` 部署,与本地 `docker-compose.yml` 的区别:
|
||||
|
||||
- 仅 `api` 映射宿主端口,且绑定 `127.0.0.1:8120`(由外层 nginx 反代 + HTTPS);`postgres`/`redis`/`minio` 不对外暴露端口,仅容器内网互通。
|
||||
- 仅 `api` 映射宿主端口,且绑定 `127.0.0.1:8120`(由外层 nginx 反代 + HTTPS);`postgres`/`redis` 不对外暴露端口,仅容器内网互通。
|
||||
- 所有服务 `restart: unless-stopped`。
|
||||
- 凭据从 `.env` 注入(见 `.env.example`),不写入仓库。
|
||||
- `api` 使用 `api/Dockerfile.prod`:运行镜像用 `scratch`(从构建镜像拷贝 ca-certs),适用于 `gcr.io/distroless` 不可达的环境;Go 模块走 `goproxy.cn`。
|
||||
|
||||
+1
-1
@@ -110,4 +110,4 @@
|
||||
|
||||
## 6. 版本
|
||||
- 本路线图随规模演进更新;任何落地改动需同步:迁移(SQL) + 本文档 +(涉及对外字段时)
|
||||
`docs/data-contract.md` / `docs/openapi.yaml`。
|
||||
`docs/data-contract.md` / `api/internal/handler/openapi.json`。
|
||||
|
||||
Reference in New Issue
Block a user