package server import ( "context" "database/sql" "log" "net/http" "strconv" "time" "git.kling.dev/jared/WorkoutTrackerAPI/internal/auth" "git.kling.dev/jared/WorkoutTrackerAPI/internal/handlers" "git.kling.dev/jared/WorkoutTrackerAPI/internal/middleware" ) type Services struct { healthcheckService handlers.HealthcheckService } type Handlers struct { } type Server struct { db *sql.DB router *http.ServeMux server *http.Server services *Services handlers *Handlers jwtManager *auth.JWTManager } type UserMeResponse struct { UserId int64 `json:"userId"` Email string `json:"email"` } func NewServer(db *sql.DB, jwtSecret string) *Server { s := &Server{ db: db, router: http.NewServeMux(), server: nil, } s.services = &Services{ healthcheckService: *handlers.NewHealthcheckService(db), } s.jwtManager = auth.NewJWTManager(jwtSecret, 60*time.Minute) s.routes() return s } func (s *Server) routes() { auth := middleware.ValidateJWT(*s.jwtManager) s.router.HandleFunc("GET /health", s.services.healthcheckService.Health) s.router.HandleFunc("POST /auth", func(w http.ResponseWriter, r *http.Request) { token, err := s.jwtManager.GenerateToken(123, "jared") if err != nil { w.WriteHeader(http.StatusInternalServerError) return } handlers.JSON(w, http.StatusOK, token) }) s.router.HandleFunc("GET /auth/me", auth(func(w http.ResponseWriter, r *http.Request) { log.Printf("Start of /auth/me") ctxUserId := r.Context().Value(middleware.UserIDKey).(string) email := r.Context().Value(middleware.EmailKey).(string) userId, _ := strconv.ParseInt(ctxUserId, 10, 64) log.Printf("Values: %d - %s", userId, email) response := UserMeResponse{ UserId: userId, Email: email, } handlers.JSON(w, http.StatusOK, response) })) } func (s *Server) Start(addr string) error { handler := middleware.Logging( middleware.CORS( s.router, ), ) server := &http.Server{ Addr: addr, Handler: handler, ReadTimeout: 15 * time.Second, WriteTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second, } s.server = server return server.ListenAndServe() } func (s *Server) Shutdown(ctx context.Context) error { if s.server == nil { return nil } return s.server.Shutdown(ctx) }