-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
88 lines (69 loc) · 1.95 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
package main
import (
"fmt"
"net/http"
"github.com/go-chi/chi"
)
func middlewareCors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "*")
w.Header().Set("Cache-control", "no-cache")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
if r != nil {
w.WriteHeader(http.StatusOK)
}
next.ServeHTTP(w, r)
})
}
func healthz(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
type apiConfig struct {
fileserverHits int
}
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 (cfg *apiConfig) reset(w http.ResponseWriter, r *http.Request) {
cfg.fileserverHits = 0
}
func (cfg *apiConfig) metrics(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hits: " + fmt.Sprint(cfg.fileserverHits)))
}
func middlewareLog(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// log.Printf("%s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
func main() {
port := "8080"
// filerootPath := "."
apicfg := &apiConfig{
fileserverHits: 0,
}
r := chi.NewRouter()
mux := http.NewServeMux()
fsHandler := http.FileServer(http.Dir("."))
spHandler := http.StripPrefix("/app", fsHandler)
r.Handle("/app/", apicfg.middlewareMetricsInc(spHandler))
r.Get("/healthz", healthz)
mux.HandleFunc("/reset", apicfg.reset)
mux.HandleFunc("/metrics", apicfg.metrics)
corsMux := middlewareCors(r)
srv := &http.Server{
Addr: ":" + port,
Handler: corsMux,
}
srv.ListenAndServe()
}