-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
92 lines (73 loc) · 2.19 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
92
package main
import (
"log"
"net/http"
"os"
"github.com/jcsmurph/chirpy/internal/database"
"github.com/joho/godotenv"
"github.com/go-chi/chi/v5"
)
type apiConfig struct {
fileserverHits int
DB *database.DB
jwtSecret string
polkaSecret string
}
func main() {
const port = "8080"
const serverFilePath = "."
godotenv.Load()
jwtSecret := os.Getenv("JWT_SECRET")
if jwtSecret == " "{
log.Fatal("JWT_Secret env variable is not set")
}
polkaSecret := os.Getenv("POLKA_SECRET")
if polkaSecret == " "{
log.Fatal("Polka_Secret env variable is not set")
}
db, err := database.NewDB("database.json")
if err != nil {
log.Fatal(err)
}
apiCfg := apiConfig{
fileserverHits: 0,
DB: db,
jwtSecret: jwtSecret,
polkaSecret: polkaSecret,
}
router := chi.NewRouter()
fsHandler := apiCfg.middlewareMetricsInc(http.StripPrefix("/app", http.FileServer(http.Dir(serverFilePath))))
// Index Handlers
router.Handle("/app", fsHandler)
router.Handle("/app/*", fsHandler)
// Metrics Handlers
apiRouter := chi.NewRouter()
apiRouter.Get("/healthz", handlerReadiness)
apiRouter.Get("/reset", apiCfg.handlerReset)
// Login Handlers
apiRouter.Post("/login", apiCfg.handlerLogin)
// Chirp Handlers
apiRouter.Post("/chirps", apiCfg.handlerChirpsCreate)
apiRouter.Get("/chirps", apiCfg.handlerChirpsRetrieve)
apiRouter.Get("/chirps/{chirpID}", apiCfg.handlerChirpsGet)
apiRouter.Delete("/chirps/{chirpID}", apiCfg.handlerChirpDelete)
// User Handlers
apiRouter.Post("/users", apiCfg.handlerUsersCreate)
apiRouter.Put("/users", apiCfg.handlerUsersUpdate)
// Token Handlers
apiRouter.Post("/refresh", apiCfg.handlerRefreshToken)
apiRouter.Post("/revoke", apiCfg.handlerRevokeToken)
// Payment Webhook
apiRouter.Post("/polka/webhooks", apiCfg.handlerUpgradeUser)
router.Mount("/api", apiRouter)
adminRouter := chi.NewRouter()
adminRouter.Get("/metrics", apiCfg.handlerMetrics)
router.Mount("/admin", adminRouter)
corsMux := middlewareCors(router)
server := http.Server{
Addr: ":" + port,
Handler: corsMux,
}
log.Printf("Serving on port: %s\n", port)
log.Fatal(server.ListenAndServe())
}