-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
83 lines (65 loc) · 2.18 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
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"github.com/joho/godotenv"
)
type apiConfig struct {
fileServerHits int
jwtSecret string
polkaApiKey string
}
func main() {
godotenv.Load()
const port = "8080"
const fileServerPathRoot = "./public/"
dbg := flag.Bool("debug", false, "Enable debug mode")
flag.Parse()
if *dbg {
debugMode()
}
apiCfg := apiConfig{
fileServerHits: 0,
jwtSecret: os.Getenv("JWT_SECRET"),
polkaApiKey: os.Getenv("POLKA_APIKEY"),
}
mux := http.NewServeMux()
mux.Handle("/app/", apiCfg.middlewareMetricsInc(http.StripPrefix("/app", http.FileServer(http.Dir(fileServerPathRoot)))))
mux.HandleFunc("GET /api/healthz", handlerReadiness)
mux.HandleFunc("GET /admin/metrics", apiCfg.handlerMetrics)
mux.HandleFunc("/api/reset", apiCfg.resetHandler)
mux.HandleFunc("POST /api/chirps", apiCfg.handlerPostChirps)
mux.HandleFunc("GET /api/chirps", handlerGetChirps)
mux.HandleFunc("GET /api/chirps/{id}", handlerGetChirpsId)
mux.HandleFunc("DELETE /api/chirps/{id}", apiCfg.handlerDeleteChirpsId)
mux.HandleFunc("POST /api/users", handlerPostUsers)
mux.HandleFunc("PUT /api/users", apiCfg.handlerPutUsers)
mux.HandleFunc("POST /api/login", apiCfg.handlerPostLogin)
mux.HandleFunc("POST /api/refresh", apiCfg.handlerPostRefresh)
mux.HandleFunc("POST /api/revoke", apiCfg.handlerPostRevoke)
mux.HandleFunc("POST /api/polka/webhooks", apiCfg.handlerPostPolkaWebhooks)
corsMux := middlewareCors(mux)
srv := &http.Server{
Addr: ":" + port,
Handler: corsMux,
}
log.Printf("Serving on port: %s\n", port)
log.Fatal(srv.ListenAndServe())
}
func (cfg *apiConfig) handlerMetrics(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf("<html>\n\n<body>\n<h1>Welcome, Chirpy Admin</h1>\n<p>Chirpy has been visited %d times!</p>\n</body>\n\n</html>\n", cfg.fileServerHits)))
}
func (cfg *apiConfig) middlewareMetricsInc(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cfg.fileServerHits++
next.ServeHTTP(w, r)
})
}
func debugMode() {
os.Remove("database.json")
}