This commit is contained in:
angelicatesvara07-crypto
2026-09-28 14:56:41 +07:00
parent f8214fda7d
commit 47f490f5a3
23 changed files with 881 additions and 72 deletions
+40 -9
View File
@@ -3,17 +3,19 @@ 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() {
if err := config.LoadEnv(); err != nil {
fmt.Fprintf(os.Stderr, "Unable to load env: %v\n", err)
os.Exit(1)
}
config.LoadEnv()
conn, err := database.Connect()
if err != nil {
@@ -22,13 +24,42 @@ func main() {
}
defer conn.Close(context.Background())
var name string
var weight int64
err = conn.QueryRow(context.Background(), "select name, weight from widgets where id=$1", 42).Scan(&name, &weight)
err = database.CreateTables(conn)
if err != nil {
fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
fmt.Fprintf(os.Stderr, "Failed to create tables: %v\n", err)
os.Exit(1)
}
fmt.Println(name, weight)
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)
}
}