Files
di-container/cmd/fx-di-modules/api.go
T

66 lines
1.5 KiB
Go
Raw Normal View History

2026-04-13 08:14:09 +03:00
package main
// API-слой — HTTP-хендлер и сервер.
// Собирает сервисы из всех доменов в единый HTTP-интерфейс.
import (
"context"
"fmt"
"log/slog"
"net"
"net/http"
"go.uber.org/fx"
)
var APIModule = fx.Module("api",
fx.Provide(newHandler),
fx.Invoke(startHTTPServer),
)
// --- Handler ---
type handler struct {
userService UserService
authService AuthService
notificationService NotificationService
}
func newHandler(userService UserService, authService AuthService, notificationService NotificationService) *handler {
return &handler{userService: userService, authService: authService, notificationService: notificationService}
}
func (h *handler) routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "ok")
})
return mux
}
// --- HTTP Server ---
func startHTTPServer(lc fx.Lifecycle, h *handler) {
srv := &http.Server{
Addr: ":8080",
Handler: h.routes(),
}
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
ln, err := net.Listen("tcp", srv.Addr)
if err != nil {
return err
}
slog.Info("HTTP-сервер запущен", "addr", srv.Addr)
go srv.Serve(ln)
return nil
},
OnStop: func(ctx context.Context) error {
slog.Info("HTTP-сервер останавливается...")
return srv.Shutdown(ctx)
},
})
}