Files
mtusi2026lab3/cmd/server/main.go
T
2026-11-09 19:51:17 +03:00

122 lines
2.8 KiB
Go

package main
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/render"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/google/uuid"
)
type Config struct {
AppInstanceID string `env:"APP_INSTANCE_ID"`
AppPort string `env:"APP_PORT"`
DatabaseURL string `env:"DATABASE_URL"`
}
type Server struct {
db *pgxpool.Pool
config Config
}
func NewServer(config Config) (*Server, error) {
db, err := pgxpool.Connect(context.Background(), config.DatabaseURL)
if err != nil {
return nil, err
}
return &Server{db: db, config: config}, nil
}
func (s *Server) Shutdown(ctx context.Context) error {
return s.db.Close()
}
func (s *Server) routes() http.Handler {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(s.addInstanceIDMiddleware)
r.Post("/api/auth/login", s.login)
r.Post("/api/auth/logout", s.logout)
r.Get("/api/messages", s.getMessages)
r.Post("/api/messages", s.postMessage)
r.Get("/health", s.health)
return r
}
func (s *Server) addInstanceIDMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Instance-Id", s.config.AppInstanceID)
next.ServeHTTP(w, r)
})
}
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
// Логика логина
}
func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
// Логика логаута
}
func (s *Server) getMessages(w http.ResponseWriter, r *http.Request) {
// Логика получения сообщений
}
func (s *Server) postMessage(w http.ResponseWriter, r *http.Request) {
// Логика создания сообщения
}
func (s *Server) health(w http.ResponseWriter, r *http.Request) {
render.JSON(w, r, map[string]string{"status": "ok", "instance": s.config.AppInstanceID})
}
func main() {
config := Config{}
// Чтение конфигурации из env
server, err := NewServer(config)
if err != nil {
panic(err)
}
r := server.routes()
srv := &http.Server{
Addr: ":" + config.AppPort,
Handler: r,
}
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
panic(err)
}
}()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT)
<-sigChan
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
panic(err)
}
}