Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8779f0fe81 | ||
|
|
04112c4fd2 | ||
|
|
9ee2d39833 | ||
|
|
b6c463beab | ||
|
|
007fc7b938 | ||
|
|
8a29423451 |
+1
-2
@@ -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=
|
||||
@@ -13,4 +11,5 @@ OPENGOODS_TRUSTED_PROXIES=
|
||||
GOODS_ADMIN_USER=admin
|
||||
GOODS_ADMIN_PASSWORD=change-me
|
||||
GOODS_ADMIN_JWT_SECRET=change-me-to-a-long-random-string
|
||||
GOODS_BACKFLOW_RATE_PER_HOUR=30
|
||||
GOODS_ADMIN_TOKEN_TTL=12h
|
||||
|
||||
@@ -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` 配置;支持格式与默认行为见部署指南。
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
@@ -34,6 +35,10 @@ func main() {
|
||||
dbURL := getenv("OPENGOODS_DATABASE_URL", "postgres://opengoods:opengoods@localhost:5432/opengoods?sslmode=disable")
|
||||
basePath := getenv("GOODS_ADMIN_BASE_PATH", "/ping")
|
||||
username := getenv("GOODS_ADMIN_USER", "admin")
|
||||
backflowRate, err := strconv.Atoi(getenv("GOODS_BACKFLOW_RATE_PER_HOUR", "30"))
|
||||
if err != nil || backflowRate < 1 {
|
||||
log.Fatalf("invalid GOODS_BACKFLOW_RATE_PER_HOUR: must be a positive integer")
|
||||
}
|
||||
tokenTTL := 12 * time.Hour
|
||||
if value := os.Getenv("GOODS_ADMIN_TOKEN_TTL"); value != "" {
|
||||
parsed, err := time.ParseDuration(value)
|
||||
@@ -89,6 +94,7 @@ func main() {
|
||||
readCache := cache.New(redisURL)
|
||||
h := adminhandler.New(adminstore.New(pool), authn, basePath, adminweb.Dist()).
|
||||
WithUsage(usage).
|
||||
WithBackflowRate(backflowRate).
|
||||
WithCache(readCache).
|
||||
WithClientIP(clientIPs)
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ type apiKeyView struct {
|
||||
// ListAPIKeys returns all issued keys with usage stats merged in.
|
||||
func (h *Handler) ListAPIKeys(w http.ResponseWriter, r *http.Request) {
|
||||
keys, err := h.store.ListAPIKeys(r.Context())
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
views := make([]apiKeyView, 0, len(keys))
|
||||
@@ -51,7 +51,7 @@ func (h *Handler) CreateAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
plaintext, row, err := h.store.CreateAPIKey(r.Context(), in, auth.UserFrom(r.Context()))
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
@@ -63,7 +63,7 @@ func (h *Handler) CreateAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// RevokeAPIKey disables a key. Subsequent requests with it are rejected.
|
||||
func (h *Handler) RevokeAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
if err := h.store.RevokeAPIKey(r.Context(), chi.URLParam(r, "id")); h.handleErr(w, err) {
|
||||
if err := h.store.RevokeAPIKey(r.Context(), chi.URLParam(r, "id")); h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "revoked"})
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
package adminhandler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
|
||||
"github.com/baicai2026-baicai/goods/api/internal/ratelimit"
|
||||
)
|
||||
|
||||
type fakeUsageLimiter struct {
|
||||
result ratelimit.Result
|
||||
key string
|
||||
limit int
|
||||
window time.Duration
|
||||
}
|
||||
|
||||
func (f *fakeUsageLimiter) Allow(_ context.Context, key string, limit int, window time.Duration) ratelimit.Result {
|
||||
f.key = key
|
||||
f.limit = limit
|
||||
f.window = window
|
||||
return f.result
|
||||
}
|
||||
|
||||
func (*fakeUsageLimiter) Usage(context.Context, string) ratelimit.UsageStat {
|
||||
return ratelimit.UsageStat{}
|
||||
}
|
||||
|
||||
func TestBackflowRateLimitReturnsRetryAfter(t *testing.T) {
|
||||
usage := &fakeUsageLimiter{
|
||||
result: ratelimit.Result{
|
||||
Allowed: false,
|
||||
ResetUnix: time.Now().Add(2 * time.Minute).Unix(),
|
||||
},
|
||||
}
|
||||
h := New(nil, nil, "/ping", nil)
|
||||
h.usage = usage
|
||||
h.WithBackflowRate(7)
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/public/backflow", nil)
|
||||
if h.allowBackflow(recorder, req, "key-id") {
|
||||
t.Fatal("allowBackflow returned true for a denied request")
|
||||
}
|
||||
if recorder.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusTooManyRequests)
|
||||
}
|
||||
retryAfter, err := strconv.Atoi(recorder.Header().Get("Retry-After"))
|
||||
if err != nil || retryAfter <= 0 {
|
||||
t.Fatalf("Retry-After = %q, want positive integer", recorder.Header().Get("Retry-After"))
|
||||
}
|
||||
if usage.key != "backflow:key-id" || usage.limit != 7 || usage.window != time.Hour {
|
||||
t.Fatalf("Allow called with key=%q limit=%d window=%v", usage.key, usage.limit, usage.window)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInternalErrorDoesNotExposeDetailsAndLogsRequestID(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
previousOutput := log.Writer()
|
||||
log.SetOutput(&logs)
|
||||
t.Cleanup(func() { log.SetOutput(previousOutput) })
|
||||
|
||||
h := New(nil, nil, "/ping", nil)
|
||||
recorder := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/ping/api/products", nil)
|
||||
req.Header.Set(middleware.RequestIDHeader, "request-123")
|
||||
handler := middleware.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h.handleErr(w, r, errors.New("sensitive database detail"))
|
||||
}))
|
||||
handler.ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusInternalServerError)
|
||||
}
|
||||
if strings.Contains(recorder.Body.String(), "sensitive database detail") {
|
||||
t.Fatalf("response exposed internal error: %s", recorder.Body.String())
|
||||
}
|
||||
if !strings.Contains(recorder.Body.String(), "服务器内部错误") || !strings.Contains(recorder.Body.String(), "internal_error") {
|
||||
t.Fatalf("response missing generic internal error: %s", recorder.Body.String())
|
||||
}
|
||||
if !strings.Contains(logs.String(), "sensitive database detail") || !strings.Contains(logs.String(), "request-123") {
|
||||
t.Fatalf("log missing error or request ID: %s", logs.String())
|
||||
}
|
||||
}
|
||||
@@ -27,15 +27,21 @@ import (
|
||||
|
||||
// Handler holds the admin dependencies.
|
||||
type Handler struct {
|
||||
store *adminstore.Store
|
||||
authn *auth.Authenticator
|
||||
basePath string
|
||||
spa fs.FS
|
||||
submitLimit *rateLimiter
|
||||
loginLimit *loginLimiter
|
||||
usage *ratelimit.Limiter
|
||||
cache cacheBumper
|
||||
clientIP *clientip.Resolver
|
||||
store *adminstore.Store
|
||||
authn *auth.Authenticator
|
||||
basePath string
|
||||
spa fs.FS
|
||||
submitLimit *rateLimiter
|
||||
loginLimit *loginLimiter
|
||||
usage usageLimiter
|
||||
backflowRate int
|
||||
cache cacheBumper
|
||||
clientIP *clientip.Resolver
|
||||
}
|
||||
|
||||
type usageLimiter interface {
|
||||
Allow(context.Context, string, int, time.Duration) ratelimit.Result
|
||||
Usage(context.Context, string) ratelimit.UsageStat
|
||||
}
|
||||
|
||||
type cacheBumper interface {
|
||||
@@ -46,13 +52,14 @@ type cacheBumper interface {
|
||||
func New(store *adminstore.Store, authn *auth.Authenticator, basePath string, spa fs.FS) *Handler {
|
||||
basePath = "/" + strings.Trim(basePath, "/")
|
||||
return &Handler{
|
||||
store: store,
|
||||
authn: authn,
|
||||
basePath: basePath,
|
||||
spa: spa,
|
||||
submitLimit: newRateLimiter(5, 10*time.Minute),
|
||||
loginLimit: newLoginLimiter(10, 20, 15*time.Minute),
|
||||
clientIP: clientip.Default(),
|
||||
store: store,
|
||||
authn: authn,
|
||||
basePath: basePath,
|
||||
spa: spa,
|
||||
submitLimit: newRateLimiter(5, 10*time.Minute),
|
||||
loginLimit: newLoginLimiter(10, 20, 15*time.Minute),
|
||||
backflowRate: 30,
|
||||
clientIP: clientip.Default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,6 +70,12 @@ func (h *Handler) WithUsage(l *ratelimit.Limiter) *Handler {
|
||||
return h
|
||||
}
|
||||
|
||||
// WithBackflowRate configures the per-key hourly backflow request limit.
|
||||
func (h *Handler) WithBackflowRate(n int) *Handler {
|
||||
h.backflowRate = n
|
||||
return h
|
||||
}
|
||||
|
||||
// WithCache attaches a cache epoch invalidator for successful admin writes.
|
||||
func (h *Handler) WithCache(c cacheBumper) *Handler {
|
||||
h.cache = c
|
||||
@@ -281,7 +294,7 @@ func (h *Handler) ListProducts(w http.ResponseWriter, r *http.Request) {
|
||||
order := r.URL.Query().Get("order")
|
||||
page, size := pageParams(r)
|
||||
items, total, err := h.store.ListProducts(r.Context(), q, sort, order, size, (page-1)*size)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
@@ -293,7 +306,7 @@ func (h *Handler) ListProducts(w http.ResponseWriter, r *http.Request) {
|
||||
// GetProduct returns full editable detail.
|
||||
func (h *Handler) GetProduct(w http.ResponseWriter, r *http.Request) {
|
||||
d, err := h.store.GetProduct(r.Context(), chi.URLParam(r, "id"))
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, d)
|
||||
@@ -316,7 +329,7 @@ func (h *Handler) CreateProduct(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusConflict, "duplicate_gtin", "该条码(GTIN)已被其它商品使用")
|
||||
return
|
||||
}
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, d)
|
||||
@@ -325,7 +338,7 @@ func (h *Handler) CreateProduct(w http.ResponseWriter, r *http.Request) {
|
||||
// Stats returns the dashboard overview counters.
|
||||
func (h *Handler) Stats(w http.ResponseWriter, r *http.Request) {
|
||||
st, err := h.store.Stats(r.Context())
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, st)
|
||||
@@ -335,7 +348,7 @@ func (h *Handler) Stats(w http.ResponseWriter, r *http.Request) {
|
||||
func (h *Handler) ListAllAudit(w http.ResponseWriter, r *http.Request) {
|
||||
page, size := pageParams(r)
|
||||
items, total, err := h.store.ListAllAudit(r.Context(), size, (page-1)*size)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
@@ -386,7 +399,7 @@ func (h *Handler) BulkProducts(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusBadRequest, "bad_request", "未选择任何商品")
|
||||
return
|
||||
}
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"status": "ok", "affected": affected})
|
||||
@@ -404,7 +417,7 @@ func (h *Handler) UpdateProduct(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
d, err := h.store.UpdateProduct(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, d)
|
||||
@@ -413,7 +426,7 @@ func (h *Handler) UpdateProduct(w http.ResponseWriter, r *http.Request) {
|
||||
// ListAudit returns audit history for a product.
|
||||
func (h *Handler) ListAudit(w http.ResponseWriter, r *http.Request) {
|
||||
items, err := h.store.ListAudit(r.Context(), chi.URLParam(r, "id"), 100)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||
@@ -430,7 +443,7 @@ func (h *Handler) AddImage(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
im, err := h.store.AddImage(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), body.URL, body.Kind)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, im)
|
||||
@@ -439,7 +452,7 @@ func (h *Handler) AddImage(w http.ResponseWriter, r *http.Request) {
|
||||
// DeleteImage removes an image.
|
||||
func (h *Handler) DeleteImage(w http.ResponseWriter, r *http.Request) {
|
||||
err := h.store.DeleteImage(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "imageID"), auth.UserFrom(r.Context()))
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||
@@ -453,7 +466,7 @@ func (h *Handler) AddMSRP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
m, err := h.store.AddMSRP(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, m)
|
||||
@@ -462,7 +475,7 @@ func (h *Handler) AddMSRP(w http.ResponseWriter, r *http.Request) {
|
||||
// DeleteMSRP removes an MSRP snapshot.
|
||||
func (h *Handler) DeleteMSRP(w http.ResponseWriter, r *http.Request) {
|
||||
err := h.store.DeleteMSRP(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "msrpID"), auth.UserFrom(r.Context()))
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||
@@ -480,7 +493,7 @@ func (h *Handler) AddBarcode(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
b, err := h.store.AddBarcode(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
|
||||
if h.handleBarcodeErr(w, err) {
|
||||
if h.handleBarcodeErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, b)
|
||||
@@ -489,7 +502,7 @@ func (h *Handler) AddBarcode(w http.ResponseWriter, r *http.Request) {
|
||||
// DeleteBarcode removes a barcode; a primary one is replaced automatically.
|
||||
func (h *Handler) DeleteBarcode(w http.ResponseWriter, r *http.Request) {
|
||||
err := h.store.DeleteBarcode(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "barcodeID"), auth.UserFrom(r.Context()))
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||
@@ -498,7 +511,7 @@ func (h *Handler) DeleteBarcode(w http.ResponseWriter, r *http.Request) {
|
||||
// SetPrimaryBarcode marks one barcode primary and mirrors it to product.gtin.
|
||||
func (h *Handler) SetPrimaryBarcode(w http.ResponseWriter, r *http.Request) {
|
||||
b, err := h.store.SetPrimaryBarcode(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "barcodeID"), auth.UserFrom(r.Context()))
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, b)
|
||||
@@ -506,7 +519,7 @@ func (h *Handler) SetPrimaryBarcode(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// handleBarcodeErr maps barcode-specific errors (GTIN validation, ownership
|
||||
// conflict) to client-facing statuses, falling back to handleErr otherwise.
|
||||
func (h *Handler) handleBarcodeErr(w http.ResponseWriter, err error) bool {
|
||||
func (h *Handler) handleBarcodeErr(w http.ResponseWriter, r *http.Request, err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
@@ -527,13 +540,13 @@ func (h *Handler) handleBarcodeErr(w http.ResponseWriter, err error) bool {
|
||||
writeError(w, http.StatusBadRequest, "invalid_gtin", err.Error())
|
||||
return true
|
||||
}
|
||||
return h.handleErr(w, err)
|
||||
return h.handleErr(w, r, err)
|
||||
}
|
||||
|
||||
// ListBrands returns brand options.
|
||||
func (h *Handler) ListBrands(w http.ResponseWriter, r *http.Request) {
|
||||
items, err := h.store.ListBrands(r.Context())
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||
@@ -547,7 +560,7 @@ func (h *Handler) ListKindFields(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
items, err := h.store.ListKindFields(r.Context(), kind)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items, "kind": kind})
|
||||
@@ -556,7 +569,7 @@ func (h *Handler) ListKindFields(w http.ResponseWriter, r *http.Request) {
|
||||
// ListCategories returns category options.
|
||||
func (h *Handler) ListCategories(w http.ResponseWriter, r *http.Request) {
|
||||
items, err := h.store.ListCategories(r.Context())
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||
@@ -574,7 +587,7 @@ func (h *Handler) CreateCategory(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
c, err := h.store.CreateCategory(r.Context(), auth.UserFrom(r.Context()), in)
|
||||
if h.handleCategoryErr(w, err) {
|
||||
if h.handleCategoryErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, c)
|
||||
@@ -592,7 +605,7 @@ func (h *Handler) UpdateCategory(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
c, err := h.store.UpdateCategory(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
|
||||
if h.handleCategoryErr(w, err) {
|
||||
if h.handleCategoryErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, c)
|
||||
@@ -601,7 +614,7 @@ func (h *Handler) UpdateCategory(w http.ResponseWriter, r *http.Request) {
|
||||
// DeleteCategory removes a leaf category that no product uses.
|
||||
func (h *Handler) DeleteCategory(w http.ResponseWriter, r *http.Request) {
|
||||
err := h.store.DeleteCategory(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()))
|
||||
if h.handleCategoryErr(w, err) {
|
||||
if h.handleCategoryErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||
@@ -609,7 +622,7 @@ func (h *Handler) DeleteCategory(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// handleCategoryErr maps category-specific errors to client statuses, falling
|
||||
// back to handleErr otherwise.
|
||||
func (h *Handler) handleCategoryErr(w http.ResponseWriter, err error) bool {
|
||||
func (h *Handler) handleCategoryErr(w http.ResponseWriter, r *http.Request, err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
@@ -627,7 +640,7 @@ func (h *Handler) handleCategoryErr(w http.ResponseWriter, err error) bool {
|
||||
writeError(w, http.StatusBadRequest, "invalid_parent", "上级分类无效(不存在或不能移动到自身/子级下)")
|
||||
return true
|
||||
}
|
||||
return h.handleErr(w, err)
|
||||
return h.handleErr(w, r, err)
|
||||
}
|
||||
|
||||
type brandInput struct {
|
||||
@@ -650,7 +663,7 @@ func (h *Handler) CreateBrand(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
b, err := h.store.CreateBrand(r.Context(), auth.UserFrom(r.Context()), in.Name)
|
||||
if h.handleBrandErr(w, err) {
|
||||
if h.handleBrandErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, b)
|
||||
@@ -668,7 +681,7 @@ func (h *Handler) UpdateBrand(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
b, err := h.store.UpdateBrand(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in.Name)
|
||||
if h.handleBrandErr(w, err) {
|
||||
if h.handleBrandErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, b)
|
||||
@@ -686,7 +699,7 @@ func (h *Handler) MergeBrands(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
b, err := h.store.MergeBrands(r.Context(), chi.URLParam(r, "id"), in.TargetID, auth.UserFrom(r.Context()))
|
||||
if h.handleBrandErr(w, err) {
|
||||
if h.handleBrandErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, b)
|
||||
@@ -695,14 +708,14 @@ func (h *Handler) MergeBrands(w http.ResponseWriter, r *http.Request) {
|
||||
// DeleteBrand removes a brand no product references.
|
||||
func (h *Handler) DeleteBrand(w http.ResponseWriter, r *http.Request) {
|
||||
err := h.store.DeleteBrand(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()))
|
||||
if h.handleBrandErr(w, err) {
|
||||
if h.handleBrandErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||
}
|
||||
|
||||
// handleBrandErr maps brand-specific errors to client statuses.
|
||||
func (h *Handler) handleBrandErr(w http.ResponseWriter, err error) bool {
|
||||
func (h *Handler) handleBrandErr(w http.ResponseWriter, r *http.Request, err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
@@ -717,7 +730,7 @@ func (h *Handler) handleBrandErr(w http.ResponseWriter, err error) bool {
|
||||
writeError(w, http.StatusBadRequest, "invalid_merge", "合并目标无效(不存在或与源品牌相同)")
|
||||
return true
|
||||
}
|
||||
return h.handleErr(w, err)
|
||||
return h.handleErr(w, r, err)
|
||||
}
|
||||
|
||||
// ---------- submissions ----------
|
||||
@@ -739,7 +752,7 @@ func (h *Handler) CreateSubmission(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
id, err := h.store.CreateSubmission(r.Context(), in, realIP(r))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
|
||||
internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]string{"id": id, "status": "pending"})
|
||||
@@ -758,12 +771,16 @@ func (h *Handler) Backflow(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusUnauthorized, "invalid_api_key", "API key 格式无效")
|
||||
return
|
||||
}
|
||||
if _, err := h.store.APIKeyByHash(r.Context(), apikey.Hash(raw)); err != nil {
|
||||
key, err := h.store.APIKeyByHash(r.Context(), apikey.Hash(raw))
|
||||
if err != nil {
|
||||
if errors.Is(err, adminstore.ErrNotFound) {
|
||||
writeError(w, http.StatusUnauthorized, "invalid_api_key", "API key 无效或已吊销")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
|
||||
internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
if !h.allowBackflow(w, r, key.ID) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -784,12 +801,29 @@ func (h *Handler) Backflow(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
sum, err := h.store.CreateBackflowSubmissions(r.Context(), items, realIP(r))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
|
||||
internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, sum)
|
||||
}
|
||||
|
||||
func (h *Handler) allowBackflow(w http.ResponseWriter, r *http.Request, keyID string) bool {
|
||||
if h.usage == nil {
|
||||
return true
|
||||
}
|
||||
res := h.usage.Allow(r.Context(), "backflow:"+keyID, h.backflowRate, time.Hour)
|
||||
if res.Allowed {
|
||||
return true
|
||||
}
|
||||
retryAfter := res.ResetUnix - time.Now().Unix()
|
||||
if retryAfter < 1 {
|
||||
retryAfter = 1
|
||||
}
|
||||
w.Header().Set("Retry-After", strconv.FormatInt(retryAfter, 10))
|
||||
writeError(w, http.StatusTooManyRequests, "rate_limited", "回流请求超过每小时限制")
|
||||
return false
|
||||
}
|
||||
|
||||
// presentedAPIKey extracts a public API key from X-API-Key or a Bearer token.
|
||||
func presentedAPIKey(r *http.Request) string {
|
||||
if v := strings.TrimSpace(r.Header.Get("X-API-Key")); v != "" {
|
||||
@@ -806,7 +840,7 @@ func (h *Handler) ListSubmissions(w http.ResponseWriter, r *http.Request) {
|
||||
status := r.URL.Query().Get("status")
|
||||
page, size := pageParams(r)
|
||||
items, total, err := h.store.ListSubmissions(r.Context(), status, size, (page-1)*size)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
pending, _ := h.store.PendingSubmissionCount(r.Context())
|
||||
@@ -818,7 +852,7 @@ func (h *Handler) ListSubmissions(w http.ResponseWriter, r *http.Request) {
|
||||
// GetSubmission returns full submission detail (admin).
|
||||
func (h *Handler) GetSubmission(w http.ResponseWriter, r *http.Request) {
|
||||
d, err := h.store.GetSubmission(r.Context(), chi.URLParam(r, "id"))
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, d)
|
||||
@@ -827,7 +861,7 @@ func (h *Handler) GetSubmission(w http.ResponseWriter, r *http.Request) {
|
||||
// ApproveSubmission applies a contribution to the product store (admin).
|
||||
func (h *Handler) ApproveSubmission(w http.ResponseWriter, r *http.Request) {
|
||||
d, err := h.store.ApproveSubmission(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()))
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, d)
|
||||
@@ -840,7 +874,7 @@ func (h *Handler) RejectSubmission(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
err := h.store.RejectSubmission(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), body.Note)
|
||||
if h.handleErr(w, err) {
|
||||
if h.handleErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "rejected"})
|
||||
@@ -855,7 +889,12 @@ func realIP(r *http.Request) string {
|
||||
return r.RemoteAddr
|
||||
}
|
||||
|
||||
func (h *Handler) handleErr(w http.ResponseWriter, err error) bool {
|
||||
func internalError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
log.Printf("adminhandler: internal error request_id=%s: %v", middleware.GetReqID(r.Context()), err)
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "服务器内部错误")
|
||||
}
|
||||
|
||||
func (h *Handler) handleErr(w http.ResponseWriter, r *http.Request, err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
@@ -867,7 +906,7 @@ func (h *Handler) handleErr(w http.ResponseWriter, err error) bool {
|
||||
writeError(w, http.StatusConflict, "conflict", "该投稿已被处理")
|
||||
return true
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", err.Error())
|
||||
internalError(w, r, err)
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ func (h *Handler) ImportBypos(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
result, err := h.store.ImportByposRecords(r.Context(), records)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "import_error", err.Error())
|
||||
internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
|
||||
@@ -24,21 +24,6 @@ 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: .
|
||||
@@ -76,4 +61,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:
|
||||
|
||||
@@ -119,6 +119,7 @@ curl "https://goods.tangshasha.com/api/v1/products/barcode/5449000000996"
|
||||
### `POST /api/public/backflow` — 批量回流未收录商品
|
||||
|
||||
- 鉴权:请求头携带 `X-API-Key: og_live_xxxxxxxx`(或 `Authorization: Bearer og_live_xxxxxxxx`)。缺失/无效/已吊销返回 `401`。
|
||||
- 限速:按 API key 使用每小时固定窗口,默认每小时 30 次,可通过 `GOODS_BACKFLOW_RATE_PER_HOUR` 配置。超限返回 `429` 和 `Retry-After`;Redis 不可用时按现有策略放行。
|
||||
- 请求体:商品对象**数组**(与公众投稿同结构),单次最多 `1000` 条。常用字段:
|
||||
|
||||
| 字段 | 必填 | 说明 |
|
||||
|
||||
@@ -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