chirpy_server/main.go

61 lines
1.5 KiB
Go
Raw 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/joho/godotenv"
_ "github.com/lib/pq"
2024-10-09 23:11:23 +02:00
)
2024-10-14 23:00:46 +02:00
type apiConfig struct {
fileserverHits atomic.Int32
2024-10-23 22:16:51 +02:00
DB *database.Queries
Platform string
2024-10-14 23:00:46 +02:00
}
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!")
}
db, err := sql.Open("postgres", dbURL)
if err != nil {
log.Fatalf("Unable to connect to db: %s", err)
}
apiCfg := &apiConfig{
fileserverHits: atomic.Int32{},
DB: database.New(db),
Platform: platform,
}
2024-10-09 23:11:23 +02:00
mux := http.NewServeMux()
2024-10-16 21:34:04 +02:00
fsHandler := apiCfg.middlewareMetricsInc(http.StripPrefix("/app", http.FileServer(http.Dir("."))))
mux.Handle("/app/", fsHandler)
mux.HandleFunc("GET /api/healthz", func(w http.ResponseWriter, req *http.Request) {
2024-10-09 23:11:23 +02:00
req.Header.Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
})
2024-10-16 21:34:04 +02:00
mux.Handle("GET /admin/metrics", http.HandlerFunc(apiCfg.serveMetrics))
mux.Handle("POST /admin/reset", http.HandlerFunc(apiCfg.serveReset))
2024-10-23 22:16:51 +02:00
mux.HandleFunc("GET /api/chirps", apiCfg.getChirps)
mux.HandleFunc("POST /api/chirps", apiCfg.chirpsCreate)
mux.HandleFunc("POST /api/users", apiCfg.createUsers)
mux.HandleFunc("GET /api/chirps/{chirpID}", apiCfg.getChirp)
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()
}