-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
118 lines (70 loc) · 2.17 KB
/
main.go
File metadata and controls
118 lines (70 loc) · 2.17 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"database/sql"
"log"
"net/http"
"os"
"sync/atomic"
_ "github.com/lib/pq"
"github.com/SandeshNarayan/chirpy/internal/database"
"github.com/joho/godotenv"
)
type apiConfig struct {
fileserverHits atomic.Int32;
dbQueries *database.Queries;
platform string
jwtSecret string
apiKey string
}
func main(){
const filepathroot = "."
const port = "8080"
godotenv.Load()
dbURL := os.Getenv("DB_URL")
if dbURL == ""{
log.Fatal("DB_URL is not set")
}
platform := os.Getenv("PLATFORM")
if platform==""{
log.Fatal("PLATFORM must be set")
}
db, err := sql.Open("postgres", dbURL)
if err!=nil {
log.Fatalf("Error opening database: %v", err)
}
dbQueries := database.New(db)
secret:= os.Getenv("SERVER_SECRET")
if secret == "" {
log.Fatal("JWT_SECRET environment variable is not set")
}
apiKey:=os.Getenv("POLKA_KEY")
apiCfg := &apiConfig{
dbQueries: dbQueries,
fileserverHits: atomic.Int32{},
platform: platform,
jwtSecret: secret,
apiKey: apiKey,
}
mux := http.NewServeMux()
fsHandler := apiCfg.middlewareMetricsInc(http.StripPrefix("/app",http.FileServer(http.Dir(filepathroot)) ))
mux.Handle("/app/", fsHandler)
mux.HandleFunc("GET /api/healthz", handlerReadiness)
mux.HandleFunc("POST /api/users", apiCfg.handlerUsersCreate)
mux.HandleFunc("POST /api/chirps", apiCfg.handlerChirpsCreate)
mux.HandleFunc("GET /api/chirps", apiCfg.handlerChirpsRetrieve)
mux.HandleFunc("GET /api/chirps/{chirpID}", apiCfg.handlerFindChirpById)
mux.HandleFunc("POST /admin/reset", apiCfg.handlerReset)
mux.HandleFunc("GET /admin/metrics", apiCfg.handlerMetrics)
mux.HandleFunc("POST /api/login", apiCfg.handlerLogin)
mux.HandleFunc("POST /api/refresh", apiCfg.handlerRefresh)
mux.HandleFunc("POST /api/revoke", apiCfg.handlerRevoke)
mux.HandleFunc("PUT /api/users", apiCfg.handlerUsersUpdate)
mux.HandleFunc("DELETE /api/chirps/{chirpID}", apiCfg.handlerChirpsDelete)
mux.HandleFunc("POST /api/polka/webhooks", apiCfg.handlerWebhooksUpdate)
server := &http.Server{
Handler : mux,
Addr : ":" + port,
}
log.Printf("Server started on port: %s\n", port)
log.Fatal(server.ListenAndServe())
}