-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathapp.go
326 lines (271 loc) · 7.58 KB
/
app.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package h
import (
"context"
"fmt"
"log/slog"
"net/http"
"os"
"os/exec"
"runtime"
"strings"
"time"
"github.com/go-chi/chi/v5"
"github.com/maddalax/htmgo/framework/hx"
"github.com/maddalax/htmgo/framework/service"
)
type RequestContext struct {
Request *http.Request
Response http.ResponseWriter
locator *service.Locator
isBoosted bool
currentBrowserUrl string
hxPromptResponse string
isHxRequest bool
hxTargetId string
hxTriggerName string
hxTriggerId string
kv map[string]interface{}
}
func GetRequestContext(r *http.Request) *RequestContext {
return r.Context().Value(RequestContextKey).(*RequestContext)
}
func (c *RequestContext) SetCookie(cookie *http.Cookie) {
http.SetCookie(c.Response, cookie)
}
func (c *RequestContext) Redirect(path string, code int) {
if code == 0 {
code = http.StatusTemporaryRedirect
}
if code < 300 || code > 399 {
code = http.StatusTemporaryRedirect
}
c.Response.Header().Set("Location", path)
c.Response.WriteHeader(code)
}
func (c *RequestContext) IsHttpPost() bool {
return c.Request.Method == http.MethodPost
}
func (c *RequestContext) IsHttpGet() bool {
return c.Request.Method == http.MethodGet
}
func (c *RequestContext) IsHttpPut() bool {
return c.Request.Method == http.MethodPut
}
func (c *RequestContext) IsHttpDelete() bool {
return c.Request.Method == http.MethodDelete
}
func (c *RequestContext) FormValue(key string) string {
return c.Request.FormValue(key)
}
func (c *RequestContext) Header(key string) string {
return c.Request.Header.Get(key)
}
func (c *RequestContext) UrlParam(key string) string {
return chi.URLParam(c.Request, key)
}
func (c *RequestContext) QueryParam(key string) string {
return c.Request.URL.Query().Get(key)
}
func (c *RequestContext) IsBoosted() bool {
return c.isBoosted
}
func (c *RequestContext) IsHxRequest() bool {
return c.isHxRequest
}
func (c *RequestContext) HxPromptResponse() string {
return c.hxPromptResponse
}
func (c *RequestContext) HxTargetId() string {
return c.hxTargetId
}
func (c *RequestContext) HxTriggerName() string {
return c.hxTriggerName
}
func (c *RequestContext) HxTriggerId() string {
return c.hxTriggerId
}
func (c *RequestContext) HxCurrentBrowserUrl() string {
return c.currentBrowserUrl
}
func (c *RequestContext) Set(key string, value interface{}) {
if c.kv == nil {
c.kv = make(map[string]interface{})
}
c.kv[key] = value
}
func (c *RequestContext) Get(key string) interface{} {
if c.kv == nil {
return nil
}
return c.kv[key]
}
// ServiceLocator returns the service locator to register and retrieve services
// Usage:
// service.Set[db.Queries](locator, service.Singleton, db.Provide)
// service.Get[db.Queries](locator)
func (c *RequestContext) ServiceLocator() *service.Locator {
return c.locator
}
type AppOpts struct {
LiveReload bool
ServiceLocator *service.Locator
Register func(app *App)
Port int
}
type App struct {
Opts AppOpts
Router *chi.Mux
}
// Start starts the htmgo server
func Start(opts AppOpts) {
router := chi.NewRouter()
instance := App{
Opts: opts,
Router: router,
}
instance.start()
}
const RequestContextKey = "htmgo.request.context"
func populateHxFields(cc *RequestContext) {
cc.isBoosted = cc.Request.Header.Get(hx.BoostedHeader) == "true"
cc.currentBrowserUrl = cc.Request.Header.Get(hx.CurrentUrlHeader)
cc.hxPromptResponse = cc.Request.Header.Get(hx.PromptResponseHeader)
cc.isHxRequest = cc.Request.Header.Get(hx.RequestHeader) == "true"
cc.hxTargetId = cc.Request.Header.Get(hx.TargetIdHeader)
cc.hxTriggerName = cc.Request.Header.Get(hx.TriggerNameHeader)
cc.hxTriggerId = cc.Request.Header.Get(hx.TriggerIdHeader)
}
func (app *App) UseWithContext(h func(w http.ResponseWriter, r *http.Request, context map[string]any)) {
app.Router.Use(func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cc := r.Context().Value(RequestContextKey).(*RequestContext)
h(w, r, cc.kv)
handler.ServeHTTP(w, r)
})
})
}
func (app *App) Use(h func(ctx *RequestContext)) {
app.Router.Use(func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cc := r.Context().Value(RequestContextKey).(*RequestContext)
h(cc)
handler.ServeHTTP(w, r)
})
})
}
func GetLogLevel() slog.Level {
// Get the log level from the environment variable
logLevel := os.Getenv("LOG_LEVEL")
switch strings.ToUpper(logLevel) {
case "DEBUG":
return slog.LevelDebug
case "INFO":
return slog.LevelInfo
case "WARN":
return slog.LevelWarn
case "ERROR":
return slog.LevelError
default:
// Default to INFO if no valid log level is set
return slog.LevelInfo
}
}
func (app *App) start() {
slog.SetLogLoggerLevel(GetLogLevel())
app.Router.Use(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cc := &RequestContext{
locator: app.Opts.ServiceLocator,
Request: r,
Response: w,
kv: make(map[string]interface{}),
}
populateHxFields(cc)
ctx := context.WithValue(r.Context(), RequestContextKey, cc)
h.ServeHTTP(w, r.WithContext(ctx))
})
})
if app.Opts.Register != nil {
app.Opts.Register(app)
}
if app.Opts.LiveReload && IsDevelopment() {
app.AddLiveReloadHandler("/dev/livereload")
}
port := ":3000"
isDefaultPort := true
if os.Getenv("PORT") != "" {
port = fmt.Sprintf(":%s", os.Getenv("PORT"))
isDefaultPort = false
}
if app.Opts.Port != 0 {
port = fmt.Sprintf(":%d", app.Opts.Port)
isDefaultPort = false
}
if isDefaultPort {
slog.Info("Using default port 3000, set PORT environment variable to change it or use AppOpts.Port")
}
slog.Info(fmt.Sprintf("Server started at localhost%s", port))
if err := http.ListenAndServe(port, app.Router); err != nil {
// If we are in watch mode, just try to kill any processes holding that port
// and try again
if IsDevelopment() && IsWatchMode() {
slog.Info("Port already in use, trying to kill the process and start again")
if runtime.GOOS == "windows" {
cmd := exec.Command("cmd", "/C", fmt.Sprintf(`for /F "tokens=5" %%i in ('netstat -aon ^| findstr :%s') do taskkill /F /PID %%i`, port))
cmd.Run()
} else {
cmd := exec.Command("bash", "-c", fmt.Sprintf("kill -9 $(lsof -ti%s)", port))
cmd.Run()
}
time.Sleep(time.Millisecond * 50)
// Try to start server again
if err := http.ListenAndServe(port, app.Router); err != nil {
slog.Error("Failed to restart server", "error", err)
panic(err)
}
}
panic(err)
}
}
func writeHtml(w http.ResponseWriter, element Ren) error {
if element == nil {
return nil
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, err := fmt.Fprint(w, Render(element, WithDocType()))
return err
}
func HtmlView(w http.ResponseWriter, page *Page) error {
// if the page is nil, do nothing, this can happen if custom response is written, such as a 302 redirect
if page == nil {
return nil
}
return writeHtml(w, page.Root)
}
func PartialViewWithHeaders(w http.ResponseWriter, headers *Headers, partial *Partial) error {
if partial == nil {
return nil
}
if partial.Headers != nil {
for s, a := range *partial.Headers {
w.Header().Set(s, a)
}
}
if headers != nil {
for s, a := range *headers {
w.Header().Set(s, a)
}
}
return writeHtml(w, partial.Root)
}
func PartialView(w http.ResponseWriter, partial *Partial) error {
if partial == nil {
return nil
}
if partial.Headers != nil {
for s, a := range *partial.Headers {
w.Header().Set(s, a)
}
}
return writeHtml(w, partial.Root)
}