Go + PostgreSQL + Valkey backend (cmd/internal/migrations), uni-app mobile frontend, PC web (web/), admin console (admin/), Android WebView container (android_project/). Build artifacts, node_modules, local env and debug screenshots excluded.
194 lines
6.2 KiB
Go
194 lines
6.2 KiB
Go
package main
|
||
|
||
import (
|
||
"context"
|
||
"log/slog"
|
||
"net/http"
|
||
"os"
|
||
"os/signal"
|
||
"syscall"
|
||
"time"
|
||
|
||
"github.com/go-chi/chi/v5"
|
||
chimw "github.com/go-chi/chi/v5/middleware"
|
||
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||
|
||
"github.com/yourorg/article-platform/internal/platform/cache"
|
||
"github.com/yourorg/article-platform/internal/platform/config"
|
||
"github.com/yourorg/article-platform/internal/platform/metrics"
|
||
"github.com/yourorg/article-platform/internal/platform/middleware"
|
||
"github.com/yourorg/article-platform/internal/platform/storage"
|
||
"github.com/yourorg/article-platform/internal/platform/store"
|
||
"github.com/yourorg/article-platform/internal/platform/telemetry"
|
||
"github.com/yourorg/article-platform/internal/repo"
|
||
api "github.com/yourorg/article-platform/internal/transport/http"
|
||
)
|
||
|
||
func main() {
|
||
log := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
|
||
slog.SetDefault(log)
|
||
|
||
cfg, err := config.Load()
|
||
if err != nil {
|
||
log.Error("配置加载失败", "err", err)
|
||
os.Exit(1)
|
||
}
|
||
|
||
initCtx, initCancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||
pool, err := store.NewPG(initCtx, cfg.PGDSN, cfg.PGMaxConns)
|
||
if err != nil {
|
||
log.Error("PostgreSQL 连接失败", "err", err)
|
||
os.Exit(1)
|
||
}
|
||
defer pool.Close()
|
||
|
||
rdb, err := store.NewValkey(initCtx, cfg.ValKeyAddr, cfg.ValKeyPass, cfg.ValKeyDB)
|
||
if err != nil {
|
||
log.Error("Valkey 连接失败", "err", err)
|
||
os.Exit(1)
|
||
}
|
||
defer rdb.Close()
|
||
initCancel()
|
||
|
||
// ── 可观测性 ──
|
||
// 追踪必须最早初始化:后续所有 span 都挂在它的 provider 上
|
||
tracerShutdown, err := telemetry.InitTracer(context.Background(), telemetry.Config{
|
||
ServiceName: "article-platform-api",
|
||
Env: cfg.Env,
|
||
OTLPEndpoint: cfg.OTLPEnabledpoint,
|
||
SampleRatio: cfg.TraceSampleRatio,
|
||
})
|
||
if err != nil {
|
||
log.Warn("追踪初始化失败,降级为仅日志", "err", err)
|
||
tracerShutdown = func(context.Context) error { return nil }
|
||
}
|
||
defer func() {
|
||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||
defer cancel()
|
||
_ = tracerShutdown(shutdownCtx)
|
||
}()
|
||
|
||
met := metrics.New()
|
||
c := cache.New(rdb, log).WithStats(metrics.CacheStats{Reg: met}).
|
||
WithSessionPolicy(cfg.JWTTTL, cfg.SessionRenewLast)
|
||
|
||
// 依赖装配:显式构造器。项目早期用 DI 框架的复杂度大于收益,
|
||
// 依赖关系一眼看穿,启动失败信息也清晰。
|
||
deps := &api.Deps{
|
||
Cfg: cfg,
|
||
Log: log,
|
||
Pool: pool,
|
||
Cache: c,
|
||
Metrics: met,
|
||
Articles: repo.NewArticleRepo(pool),
|
||
Users: repo.NewUserRepo(pool),
|
||
Comments: repo.NewCommentRepo(pool),
|
||
Notifs: repo.NewNotificationRepo(pool),
|
||
Interacts: repo.NewInteractionRepo(pool),
|
||
Taxonomy: repo.NewTaxonomyRepo(pool),
|
||
Stats: repo.NewStatsRepo(pool),
|
||
Reports: repo.NewReportRepo(pool),
|
||
Outbox: repo.NewOutboxRepo(pool),
|
||
Media: repo.NewMediaRepo(pool),
|
||
Topics: repo.NewTopicRepo(pool),
|
||
Templates: repo.NewTemplateRepo(pool),
|
||
Settings: repo.NewSettingsRepo(pool),
|
||
}
|
||
|
||
// 对象存储未配置时 Presigner 为 nil,媒体接口返回 503 而不是崩掉。
|
||
// 本地开发不需要 S3 也能跑通除上传外的全部功能。
|
||
if cfg.S3.Endpoint != "" && cfg.S3.AccessKey != "" {
|
||
deps.Presigner = &storage.Presigner{
|
||
Endpoint: cfg.S3.Endpoint,
|
||
Region: cfg.S3.Region,
|
||
Bucket: cfg.S3.Bucket,
|
||
AccessKey: cfg.S3.AccessKey,
|
||
SecretKey: cfg.S3.SecretKey,
|
||
PublicBase: cfg.S3.PublicBase,
|
||
}
|
||
log.Info("对象存储已配置", "bucket", cfg.S3.Bucket)
|
||
} else {
|
||
log.Warn("对象存储未配置,上传接口将返回 503")
|
||
}
|
||
deps.Auth = &middleware.Auth{Cache: c, Users: deps.Users, Pool: pool, Log: log, Metrics: met}
|
||
deps.RateLimit = middleware.NewRateLimiter(c,
|
||
cfg.RateLimit.AnonPerMinute, cfg.RateLimit.UserPerMinute)
|
||
deps.RateLimit.Metrics = met
|
||
|
||
r := chi.NewRouter()
|
||
|
||
// CORS 必须第一个:预检 OPTIONS 请求不带 Authorization,
|
||
// 如果排在认证中间件后面会被当成未登录拒绝
|
||
r.Use(middleware.NewCORS(cfg.CORSOrigins, cfg.Env != "prod").Middleware)
|
||
r.Use(chimw.RequestID)
|
||
r.Use(chimw.RealIP)
|
||
r.Use(chimw.Recoverer) // panic 不炸进程
|
||
r.Use(chimw.Timeout(20 * time.Second))
|
||
// 追踪包在最外层:这样连认证、限流耗时的 spans 都能看到
|
||
r.Use(otelhttp.NewMiddleware("http.server",
|
||
otelhttp.WithSpanNameFormatter(func(_ string, req *http.Request) string {
|
||
return req.Method + " " + req.URL.Path
|
||
}),
|
||
))
|
||
r.Use(met.Middleware)
|
||
r.Use(requestLogger(log))
|
||
r.Use(deps.Auth.Middleware)
|
||
r.Use(deps.RateLimit.Middleware)
|
||
|
||
// /metrics 必须在所有 Use 之后注册(chi 要求中间件先于路由定义)。
|
||
// metrics.Middleware 内部已把 /metrics 自身排除在采集之外,
|
||
// 所以抓取行为不会污染业务指标。
|
||
r.Handle("/metrics", met.Handler())
|
||
|
||
api.Mount(r, deps)
|
||
|
||
srv := &http.Server{
|
||
Addr: cfg.HTTPAddr,
|
||
Handler: r,
|
||
ReadHeaderTimeout: 5 * time.Second,
|
||
ReadTimeout: 15 * time.Second,
|
||
WriteTimeout: 30 * time.Second,
|
||
IdleTimeout: 120 * time.Second,
|
||
MaxHeaderBytes: 1 << 20,
|
||
}
|
||
|
||
go func() {
|
||
log.Info("HTTP 服务启动", "addr", cfg.HTTPAddr, "env", cfg.Env)
|
||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||
log.Error("HTTP 服务异常退出", "err", err)
|
||
os.Exit(1)
|
||
}
|
||
}()
|
||
|
||
// 优雅关闭:停止接新请求,等存量请求跑完(最多 20 秒)
|
||
quit := make(chan os.Signal, 1)
|
||
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||
<-quit
|
||
|
||
log.Info("开始优雅关闭")
|
||
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||
defer shutdownCancel()
|
||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||
log.Error("优雅关闭超时", "err", err)
|
||
}
|
||
log.Info("已停止")
|
||
}
|
||
|
||
func requestLogger(l *slog.Logger) func(http.Handler) http.Handler {
|
||
return func(next http.Handler) http.Handler {
|
||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
start := time.Now()
|
||
ww := chimw.NewWrapResponseWriter(w, r.ProtoMajor)
|
||
next.ServeHTTP(ww, r)
|
||
l.Info("request",
|
||
"method", r.Method,
|
||
"path", r.URL.Path,
|
||
"status", ww.Status(),
|
||
"bytes", ww.BytesWritten(),
|
||
"dur_ms", time.Since(start).Milliseconds(),
|
||
"req_id", chimw.GetReqID(r.Context()),
|
||
)
|
||
})
|
||
}
|
||
}
|