forked from mtusi2026/mtusi2026lab2
193 lines
4.2 KiB
Go
193 lines
4.2 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"log"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
)
|
|
|
|
type healthResponse struct {
|
|
Status string `json:"status"`
|
|
}
|
|
type apiError struct {
|
|
Code string `json:"code"`
|
|
Message string `json:"message"`
|
|
RequestID string `json:"request_id"`
|
|
}
|
|
|
|
type errorResponse struct {
|
|
Error apiError `json:"error"`
|
|
}
|
|
|
|
func newRequestID() string {
|
|
bytes := make([]byte, 16)
|
|
|
|
if _, err := rand.Read(bytes); err != nil {
|
|
return "request-id-generation-failed"
|
|
}
|
|
|
|
return hex.EncodeToString(bytes)
|
|
}
|
|
|
|
func writeError(w http.ResponseWriter, status int, code string, message string, requestID string) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
|
|
response := errorResponse{
|
|
Error: apiError{
|
|
Code: code,
|
|
Message: message,
|
|
RequestID: requestID,
|
|
},
|
|
}
|
|
|
|
if err := json.NewEncoder(w).Encode(response); err != nil {
|
|
log.Printf("failed to encode error response: %v", err)
|
|
}
|
|
}
|
|
|
|
func healthHandler(w http.ResponseWriter, r *http.Request) {
|
|
requestID := newRequestID()
|
|
w.Header().Set("X-Request-Id", requestID)
|
|
|
|
if r.Method != http.MethodGet {
|
|
writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "method not allowed", requestID)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
response := healthResponse{
|
|
Status: "ok",
|
|
}
|
|
|
|
if err := json.NewEncoder(w).Encode(response); err != nil {
|
|
log.Printf("failed to encode health response: %v", err)
|
|
}
|
|
}
|
|
|
|
func readyHandler(db *pgxpool.Pool) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
requestID := newRequestID()
|
|
w.Header().Set("X-Request-Id", requestID)
|
|
if r.Method != http.MethodGet {
|
|
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
|
defer cancel()
|
|
if err := db.Ping(ctx); err != nil {
|
|
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(healthResponse{"ok"})
|
|
}
|
|
}
|
|
|
|
func serverAddress() string {
|
|
host := os.Getenv("APP_HOST")
|
|
if host == "" {
|
|
host = "0.0.0.0"
|
|
}
|
|
|
|
port := os.Getenv("APP_PORT")
|
|
if port == "" {
|
|
port = "8080"
|
|
}
|
|
|
|
return net.JoinHostPort(host, port)
|
|
}
|
|
|
|
func main() {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
db, err := openDatabase(ctx)
|
|
cancel()
|
|
if err != nil {
|
|
log.Fatalf("database initialization failed: %v", err)
|
|
}
|
|
defer db.Close()
|
|
userStore := newUserStore(db)
|
|
chatStore := newChatStore(db)
|
|
messageStore := newMessageStore(db)
|
|
sessions, err := newSessionStore(db)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
mux := http.NewServeMux()
|
|
|
|
mux.HandleFunc("/health/live", healthHandler)
|
|
mux.HandleFunc("/health/ready", readyHandler(db))
|
|
mux.Handle("/api/v1/users", createUserHandler(userStore))
|
|
mux.Handle("/api/v1/auth/sessions", sessionHandler(userStore, sessions))
|
|
mux.Handle("/api/v1/auth/sessions/current", authRequired(sessions, logoutHandler(sessions)))
|
|
mux.Handle("/api/v1/users/me", authRequired(sessions, currentUserHandler(userStore)))
|
|
mux.Handle(
|
|
"/api/v1/chats",
|
|
authRequired(sessions, chatCollectionHandler(userStore, chatStore)),
|
|
)
|
|
mux.Handle(
|
|
"/api/v1/chats/",
|
|
authRequired(sessions, chatSubresourceHandler(
|
|
userStore,
|
|
chatStore,
|
|
messageStore,
|
|
)),
|
|
)
|
|
|
|
server := &http.Server{
|
|
Addr: serverAddress(),
|
|
Handler: mux,
|
|
}
|
|
|
|
shutdownContext, stop := signal.NotifyContext(
|
|
context.Background(),
|
|
os.Interrupt,
|
|
syscall.SIGTERM,
|
|
)
|
|
defer stop()
|
|
|
|
serverErrors := make(chan error, 1)
|
|
|
|
go func() {
|
|
log.Printf("server is listening on %s", server.Addr)
|
|
|
|
if err := server.ListenAndServe(); err != nil &&
|
|
!errors.Is(err, http.ErrServerClosed) {
|
|
serverErrors <- err
|
|
}
|
|
}()
|
|
|
|
select {
|
|
case err := <-serverErrors:
|
|
log.Printf("server error: %v", err)
|
|
|
|
case <-shutdownContext.Done():
|
|
log.Printf("shutdown signal received")
|
|
|
|
shutdownDeadline, cancel := context.WithTimeout(
|
|
context.Background(),
|
|
10*time.Second,
|
|
)
|
|
defer cancel()
|
|
|
|
if err := server.Shutdown(shutdownDeadline); err != nil {
|
|
log.Printf("graceful shutdown failed: %v", err)
|
|
return
|
|
}
|
|
|
|
log.Printf("server stopped gracefully")
|
|
}
|
|
}
|