-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
103 lines (80 loc) · 2.37 KB
/
main.go
File metadata and controls
103 lines (80 loc) · 2.37 KB
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
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"database/sql"
"fmt"
"io"
"log"
"net/http"
"os"
"sync/atomic"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
"github.com/mdmdj/bootdev-chirpy/internal/database"
)
type apiConfig struct {
addr string
fileserverHits atomic.Int32
db *database.Queries
platform string
secret string
polkaKey string
}
var cfg apiConfig
func (cfg *apiConfig) middlewareMetricsInc(next http.Handler) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
fmt.Println("increment fileserverHits")
fmt.Println(cfg.fileserverHits.Load())
cfg.fileserverHits.Add(1)
fmt.Println(cfg.fileserverHits.Load())
fmt.Println("call next")
next.ServeHTTP(w, r)
})
}
func main() {
godotenv.Load()
cfg.platform = os.Getenv("PLATFORM")
cfg.secret = os.Getenv("TOKEN_SECRET")
cfg.polkaKey = os.Getenv("POLKA_KEY")
//Setup DB
dbURL := os.Getenv("DB_URL")
db, err := sql.Open("postgres", dbURL)
if err != nil {
log.Fatalln(err)
}
dbQueries := database.New(db)
cfg.db = dbQueries
// Setup Server
cfg.addr = ":8080"
// Setup Routes
mux := http.NewServeMux()
server := http.Server{
Addr: cfg.addr,
Handler: mux,
}
appFileHandler := http.StripPrefix("/app", http.FileServer(http.Dir(".")))
mux.Handle("/app/", cfg.middlewareMetricsInc(appFileHandler))
mux.HandleFunc("GET /api/healthz", healthzRoute)
mux.HandleFunc("GET /admin/metrics", cfg.metricsRoute)
mux.HandleFunc("POST /admin/reset", cfg.resetRoute)
mux.HandleFunc("GET /api/chirps", chirpGetAllRoute)
mux.HandleFunc("GET /api/chirps/{chirpID}", chirpGetOneRoute)
mux.HandleFunc("DELETE /api/chirps/{chirpID}", chirpDeleteOneRoute)
mux.HandleFunc("POST /api/chirps", chirpCreateRoute)
mux.HandleFunc("POST /api/users", userCreateRoute)
mux.HandleFunc("PUT /api/users", userUpdateRoute)
mux.HandleFunc("POST /api/login", userLoginRoute)
mux.HandleFunc("POST /api/refresh", refreshRoute)
mux.HandleFunc("POST /api/revoke", revokeRoute)
mux.HandleFunc("POST /api/polka/webhooks", polkaWebhooksRoute)
// Start Server
fmt.Println("starting server on ", cfg.addr)
err = server.ListenAndServe()
fmt.Println(err)
}
func healthzRoute(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
fmt.Println("healthz OK")
io.WriteString(w, "OK")
}