Files
language/backend/internal/app/app.go
T
fish 71a6bc4aa4 新增语言学习后台服务
- 分类管理:支持分类的增删改查
- 单词管理:支持单词的增删改查,包含音标、释义、例句等字段
- 更新 README 项目说明

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-16 22:38:09 +08:00

69 lines
1.6 KiB
Go

package app
import (
"net/http"
"github.com/fish/language/backend/internal/config"
"github.com/fish/language/backend/internal/handlers"
"github.com/fish/language/backend/internal/repository/queries"
"github.com/fish/language/backend/internal/services"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/jackc/pgx/v5/pgxpool"
)
// App wires all dependencies and exposes the HTTP server.
type App struct {
cfg *config.Config
router *chi.Mux
pool *pgxpool.Pool
}
// New creates and initializes a new App.
func New(cfg *config.Config, pool *pgxpool.Pool) *App {
app := &App{
cfg: cfg,
pool: pool,
}
app.setupRouter()
return app
}
func (a *App) setupRouter() {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.SetHeader("Content-Type", "application/json"))
q := queries.New(a.pool)
categorySvc := services.NewCategoryService(q)
wordSvc := services.NewWordService(q)
categoryHandler := handlers.NewCategoryHandler(categorySvc)
wordHandler := handlers.NewWordHandler(wordSvc)
r.Route("/api/v1", func(api chi.Router) {
categoryHandler.Register(api)
wordHandler.Register(api)
})
r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"ok"}`))
})
a.router = r
}
// Router returns the underlying chi router for testing.
func (a *App) Router() *chi.Mux {
return a.router
}
// Run starts the HTTP server.
func (a *App) Run() error {
return http.ListenAndServe(a.cfg.HTTPAddr, a.router)
}