/
main.go
187 lines (152 loc) · 3.7 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
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package main
import (
"embed"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"time"
stats_api "github.com/fukata/golang-stats-api-handler"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
// Version is to embed the version string
var Version = "202309030000"
//go:embed dummy.json
var embeddedFS embed.FS
type response struct {
Version string `json:"version"`
Now time.Time `json:"now"`
}
func printNow(w io.Writer) {
err := json.NewEncoder(w).Encode(&response{
Version: Version,
Now: time.Now(),
})
if err != nil {
log.Print("ERROR:", err)
}
}
func main() {
var httpMode = flag.Bool("http", true, "enable HTTP server")
var devMode = flag.Bool("dev", true, "enable the proxy for the next dev server")
flag.Parse()
if *httpMode {
HTTP(*devMode)
} else {
for range time.Tick(10 * time.Second) {
printNow(os.Stdout)
}
}
}
func RequestIDWriter(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqID := middleware.GetReqID(r.Context())
if reqID != "" {
w.Header().Add("X-Request-ID", reqID)
}
next.ServeHTTP(w, r)
})
}
// HTTP runs the HTTP server
func HTTP(devMode bool) {
port := os.Getenv("PORT")
host := os.Getenv("HOST")
if port == "" {
port = "8000"
}
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(RequestIDWriter)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Route("/api", func(r chi.Router) {
r.Get("/ping", func(w http.ResponseWriter, r *http.Request) {
if dur := r.URL.Query().Get("sleep"); dur != "" {
duration, err := time.ParseDuration(dur)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
time.Sleep(duration)
}
w.Header().Add("Content-Type", "application/json")
printNow(w)
})
r.Get("/events", func(w http.ResponseWriter, r *http.Request) {
defer func() {
log.Println("INFO: events: client disconnect")
}()
flusher, ok := w.(http.Flusher)
if !ok {
log.Println("ERROR: no flusher found")
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-store")
t := time.NewTicker(1 * time.Second)
defer t.Stop()
go func() {
for {
select {
case now := <-t.C:
fmt.Fprintf(w, "data: %d\n\n", now.Unix())
flusher.Flush()
}
}
}()
<-r.Context().Done()
})
r.Get("/json", staticFileServer(
http.FS(embeddedFS),
"dummy.json",
))
r.Get("/_stats", stats_api.Handler)
})
if devMode {
log.Print("Setting the proxy for the next dev server...")
// proxy to the local next dev server
rpURL, err := url.Parse("http://localhost:3000")
if err != nil {
log.Fatal(err)
}
r.Handle("/*", &httputil.ReverseProxy{
Rewrite: func(r *httputil.ProxyRequest) {
r.SetXForwarded()
r.SetURL(rpURL)
},
})
} else {
r.Handle("/*", http.FileServer(http.Dir("./public")))
}
log.Printf("Listening to %s", host+":"+port)
http.ListenAndServe(host+":"+port, r)
}
func staticFileServer(hfs http.FileSystem, fn string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
f, err := hfs.Open(fn)
switch {
case errors.Is(err, fs.ErrNotExist):
http.Error(w, "Not Found", http.StatusNotFound)
return
case err != nil:
http.Error(w, fmt.Errorf("opening file: %w", err).Error(), http.StatusInternalServerError)
return
}
defer f.Close()
d, err := f.Stat()
if err != nil {
http.Error(w, fmt.Errorf("reading file: %w", err).Error(), http.StatusInternalServerError)
return
}
http.ServeContent(w, r, fn, d.ModTime(), f)
}
}