-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhttpHandler.go
56 lines (48 loc) · 1.24 KB
/
httpHandler.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
//go:build !wasm
package rui
import (
"net/http"
"strings"
)
type httpHandler struct {
app *application
prefix string
}
func (h *httpHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
switch req.Method {
case http.MethodGet:
path := `/` + strings.TrimPrefix(req.URL.Path, `/`)
req.URL.Path = `/` + strings.TrimPrefix(strings.TrimPrefix(path, h.prefix), `/`)
h.app.ServeHTTP(w, req)
}
}
// NewHandler is used to embed the rui application in third-party web frameworks (net/http, gin, echo...).
//
// Example for echo:
//
// e := echo.New()
// e.Any(`/ui/*`, func()echo.HandlerFunc{
// rui.AddEmbedResources(&resources)
//
// h := rui.NewHandler("/ui", CreateSessionContent, rui.AppParams{
// Title: `Awesome app`,
// Icon: `favicon.png`,
// })
//
// return func(c echo.Context) error {
// h.ServeHTTP(c.Response(), c.Request())
// return nil
// }
// })
func NewHandler(urlPrefix string, createContentFunc func(Session) SessionContent, params AppParams) *httpHandler {
app := new(application)
app.params = params
app.sessions = map[int]sessionInfo{}
app.createContentFunc = createContentFunc
apps = append(apps, app)
h := &httpHandler{
app: app,
prefix: `/` + strings.Trim(urlPrefix, `/`),
}
return h
}