chirpy_server/cmd/server/main.go

73 lines
1.9 KiB
Go
Raw Permalink Normal View History

2024-10-09 23:11:23 +02:00
package main
import (
2024-10-23 22:16:51 +02:00
"database/sql"
"log"
2024-10-09 23:11:23 +02:00
"net/http"
2024-10-23 22:16:51 +02:00
"os"
2024-10-14 23:00:46 +02:00
"sync/atomic"
2024-10-23 22:16:51 +02:00
"github.com/finchrelia/chirpy-server/internal/database"
"github.com/finchrelia/chirpy-server/internal/handler"
2024-10-23 22:16:51 +02:00
"github.com/joho/godotenv"
_ "github.com/lib/pq"
2024-10-09 23:11:23 +02:00
)
func main() {
2024-10-23 22:16:51 +02:00
godotenv.Load()
dbURL := os.Getenv("DB_URL")
if dbURL == "" {
log.Fatalf("Empty dbURL !")
}
platform := os.Getenv("PLATFORM")
if platform == "" {
log.Fatalf("Empty PLATFORM env var!")
}
2024-10-25 23:31:57 +02:00
jwtSecret := os.Getenv("JWT_SECRET")
if jwtSecret == "" {
log.Fatalf("Empty JWT_SECRET env var!")
}
2024-10-26 15:03:14 +02:00
polkaKey := os.Getenv("POLKA_KEY")
if polkaKey == "" {
log.Fatalf("Empty POLKA_KEY env var!")
}
2024-10-23 22:16:51 +02:00
db, err := sql.Open("postgres", dbURL)
if err != nil {
log.Fatalf("Unable to connect to db: %v", err)
2024-10-23 22:16:51 +02:00
}
apiCfg := &handler.APIConfig{
FileserverHits: atomic.Int32{},
2024-10-23 22:16:51 +02:00
DB: database.New(db),
Platform: platform,
2024-10-25 23:31:57 +02:00
JWT: jwtSecret,
2024-10-26 15:03:14 +02:00
PolkaKey: polkaKey,
2024-10-23 22:16:51 +02:00
}
2024-10-09 23:11:23 +02:00
mux := http.NewServeMux()
fsHandler := apiCfg.MiddlewareMetricsInc(http.StripPrefix("/app", http.FileServer(http.Dir("."))))
2024-10-16 21:34:04 +02:00
mux.Handle("/app/", fsHandler)
mux.HandleFunc("GET /api/healthz", handler.Readiness)
mux.HandleFunc("POST /api/polka/webhooks", apiCfg.SubscribeUser)
mux.HandleFunc("POST /api/login", apiCfg.Login)
2024-10-25 23:31:57 +02:00
mux.HandleFunc("POST /api/refresh", apiCfg.RefreshToken)
mux.HandleFunc("POST /api/revoke", apiCfg.RevokeToken)
mux.Handle("GET /admin/metrics", http.HandlerFunc(apiCfg.Metrics))
mux.Handle("POST /admin/reset", http.HandlerFunc(apiCfg.Reset))
mux.HandleFunc("GET /api/chirps", apiCfg.GetChirps)
mux.HandleFunc("POST /api/chirps", apiCfg.ChirpsCreate)
mux.HandleFunc("GET /api/chirps/{chirpID}", apiCfg.GetChirp)
mux.HandleFunc("DELETE /api/chirps/{chirpID}", apiCfg.DeleteChirp)
mux.HandleFunc("POST /api/users", apiCfg.CreateUsers)
mux.HandleFunc("PUT /api/users", apiCfg.UpdateUsers)
2024-10-14 23:00:46 +02:00
2024-10-09 23:11:23 +02:00
server := &http.Server{
Addr: ":8080",
Handler: mux,
}
server.ListenAndServe()
}