-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
91 lines (77 loc) · 2.31 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"sync/atomic"
"example.com/chirpy/internal/database"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
)
type apiConfig struct {
fileServerHits atomic.Int32
dbQueries *database.Queries
platform string
jwtSecret string
polkaKey string
}
func main() {
godotenv.Load()
dbURL := os.Getenv("DB_URL")
if dbURL == "" {
fmt.Print("Unable to load DB_URL")
return
}
db, err := sql.Open("postgres", dbURL)
if err != nil {
log.Printf("Failed to connect to database: %s", err)
}
dbQueries := database.New(db)
platform := os.Getenv("PLATFORM")
if platform == "" {
fmt.Println("Unable to load PLATFORM")
return
}
jwtSecret := os.Getenv("JWT_SECRET")
if jwtSecret == "" {
fmt.Println("Unable to load JWT_SECRET")
return
}
polkaKey := os.Getenv("POLKA_KEY")
if polkaKey == "" {
fmt.Println("Unable to load Polka Key")
return
}
const port string = "8080"
const root string = "."
apiConfig := apiConfig{
fileServerHits: atomic.Int32{},
dbQueries: dbQueries,
platform: platform,
jwtSecret: jwtSecret,
polkaKey: polkaKey,
}
mux := http.NewServeMux()
mux.Handle("/app/", http.StripPrefix("/app/", apiConfig.middleWareMetricsInc(http.FileServer(http.Dir(root)))))
mux.HandleFunc("GET /api/healthz", handlerReadiness)
mux.HandleFunc("GET /admin/metrics", apiConfig.handlerMetricsShow)
mux.HandleFunc("POST /admin/reset", apiConfig.handlerReset)
mux.HandleFunc("POST /api/users", apiConfig.handlerCreateUser)
mux.HandleFunc("PUT /api/users", apiConfig.handlerUpdateUser)
mux.HandleFunc("POST /api/chirps", apiConfig.handlerCreateChirp)
mux.HandleFunc("GET /api/chirps", apiConfig.handlerGetAllChirps)
mux.HandleFunc("GET /api/chirps/{chirpID}", apiConfig.handlerGetChirp)
mux.HandleFunc("DELETE /api/chirps/{chirpID}", apiConfig.handlerDeleteChirp)
mux.HandleFunc("POST /api/login", apiConfig.handlerLogin)
mux.HandleFunc("POST /api/revoke", apiConfig.handlerRevokeRefreshToken)
mux.HandleFunc("POST /api/refresh", apiConfig.handlerUpdateRefreshToken)
mux.HandleFunc("POST /api/polka/webhooks", apiConfig.handlerEnableChirpyRed)
server := http.Server{
Addr: ":" + port,
Handler: mux,
}
fmt.Printf("Serving files from %s on port %s\n", root, port)
log.Fatal(server.ListenAndServe())
}