Files
wo4_15_AngelicaTA_restAPI/cmd/server/main.go
T
2026-09-28 14:56:41 +07:00

66 lines
1.8 KiB
Go

package main
import (
"context"
"fmt"
"net/http"
"os"
"sync"
"5803025015/w04/internal/config"
"5803025015/w04/internal/database"
"5803025015/w04/internal/handler"
"5803025015/w04/internal/middleware"
"5803025015/w04/internal/store"
)
func main() {
config.LoadEnv()
conn, err := database.Connect()
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
os.Exit(1)
}
defer conn.Close(context.Background())
err = database.CreateTables(conn)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create tables: %v\n", err)
os.Exit(1)
}
fmt.Println("Database connected and tables created successfully!")
mu := &sync.Mutex{}
userStore := store.NewUserStore(conn, mu)
sessionStore := store.NewSessionStore(conn, mu)
snippetStore := store.NewSnippetStore(conn, mu)
authHandler := handler.NewAuthHandler(userStore, sessionStore)
snippetHandler := handler.NewSnippetHandler(snippetStore)
authMiddleware := middleware.NewAuthMiddleware(sessionStore)
mux := http.NewServeMux()
mux.HandleFunc("POST /register", authHandler.Register)
mux.HandleFunc("POST /login", authHandler.Login)
mux.Handle("POST /logout", authMiddleware.RequireAuth(http.HandlerFunc(authHandler.Logout)))
mux.Handle("GET /snippets", authMiddleware.RequireAuth(http.HandlerFunc(snippetHandler.List)))
mux.Handle("POST /snippets", authMiddleware.RequireAuth(http.HandlerFunc(snippetHandler.Create)))
mux.Handle("GET /snippets/{id}", authMiddleware.RequireAuth(http.HandlerFunc(snippetHandler.Get)))
mux.Handle("DELETE /snippets/{id}", authMiddleware.RequireAuth(http.HandlerFunc(snippetHandler.Delete)))
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
fmt.Printf("Server listening on :%s\n", port)
if err := http.ListenAndServe(":"+port, mux); err != nil {
fmt.Fprintf(os.Stderr, "Server error: %v\n", err)
os.Exit(1)
}
}