Eric Bower
·
27 Oct 24
router.go
1package shared
2
3import (
4 "context"
5 "fmt"
6 "log/slog"
7 "net"
8 "net/http"
9 "net/http/pprof"
10 "regexp"
11 "strings"
12
13 "github.com/charmbracelet/ssh"
14 "github.com/picosh/pico/db"
15 "github.com/picosh/pico/shared/storage"
16)
17
18type Route struct {
19 Method string
20 Regex *regexp.Regexp
21 Handler http.HandlerFunc
22 CorsEnabled bool
23}
24
25func NewRoute(method, pattern string, handler http.HandlerFunc) Route {
26 return Route{
27 method,
28 regexp.MustCompile("^" + pattern + "$"),
29 handler,
30 false,
31 }
32}
33
34func NewCorsRoute(method, pattern string, handler http.HandlerFunc) Route {
35 return Route{
36 method,
37 regexp.MustCompile("^" + pattern + "$"),
38 handler,
39 true,
40 }
41}
42
43func CreatePProfRoutes(routes []Route) []Route {
44 return append(routes,
45 NewRoute("GET", "/debug/pprof/cmdline", pprof.Cmdline),
46 NewRoute("GET", "/debug/pprof/profile", pprof.Profile),
47 NewRoute("GET", "/debug/pprof/symbol", pprof.Symbol),
48 NewRoute("GET", "/debug/pprof/trace", pprof.Trace),
49 NewRoute("GET", "/debug/pprof/(.*)", pprof.Index),
50 NewRoute("POST", "/debug/pprof/cmdline", pprof.Cmdline),
51 NewRoute("POST", "/debug/pprof/profile", pprof.Profile),
52 NewRoute("POST", "/debug/pprof/symbol", pprof.Symbol),
53 NewRoute("POST", "/debug/pprof/trace", pprof.Trace),
54 NewRoute("POST", "/debug/pprof/(.*)", pprof.Index),
55 )
56}
57
58type ApiConfig struct {
59 Cfg *ConfigSite
60 Dbpool db.DB
61 Storage storage.StorageServe
62 AnalyticsQueue chan *db.AnalyticsVisits
63}
64
65func (hc *ApiConfig) CreateCtx(prevCtx context.Context, subdomain string) context.Context {
66 ctx := context.WithValue(prevCtx, ctxLoggerKey{}, hc.Cfg.Logger)
67 ctx = context.WithValue(ctx, CtxSubdomainKey{}, subdomain)
68 ctx = context.WithValue(ctx, ctxDBKey{}, hc.Dbpool)
69 ctx = context.WithValue(ctx, ctxStorageKey{}, hc.Storage)
70 ctx = context.WithValue(ctx, ctxCfg{}, hc.Cfg)
71 ctx = context.WithValue(ctx, ctxAnalyticsQueue{}, hc.AnalyticsQueue)
72 return ctx
73}
74
75func CreateServeBasic(routes []Route, ctx context.Context) http.HandlerFunc {
76 return func(w http.ResponseWriter, r *http.Request) {
77 var allow []string
78 for _, route := range routes {
79 matches := route.Regex.FindStringSubmatch(r.URL.Path)
80 if len(matches) > 0 {
81 if r.Method == "OPTIONS" && route.CorsEnabled {
82 CorsHeaders(w.Header())
83 w.WriteHeader(http.StatusOK)
84 return
85 } else if r.Method != route.Method {
86 allow = append(allow, route.Method)
87 continue
88 }
89
90 if route.CorsEnabled {
91 CorsHeaders(w.Header())
92 }
93
94 finctx := context.WithValue(ctx, ctxKey{}, matches[1:])
95 route.Handler(w, r.WithContext(finctx))
96 return
97 }
98 }
99 if len(allow) > 0 {
100 w.Header().Set("Allow", strings.Join(allow, ", "))
101 http.Error(w, "405 method not allowed", http.StatusMethodNotAllowed)
102 return
103 }
104 http.NotFound(w, r)
105 }
106}
107
108func GetSubdomainFromRequest(r *http.Request, domain, space string) string {
109 hostDomain := strings.ToLower(strings.Split(r.Host, ":")[0])
110 appDomain := strings.ToLower(strings.Split(domain, ":")[0])
111
112 if hostDomain != appDomain {
113 if strings.Contains(hostDomain, appDomain) {
114 subdomain := strings.TrimSuffix(hostDomain, fmt.Sprintf(".%s", appDomain))
115 return subdomain
116 } else {
117 subdomain := GetCustomDomain(hostDomain, space)
118 return subdomain
119 }
120 }
121
122 return ""
123}
124
125func findRouteConfig(r *http.Request, routes []Route, subdomainRoutes []Route, cfg *ConfigSite) ([]Route, string) {
126 subdomain := GetSubdomainFromRequest(r, cfg.Domain, cfg.Space)
127 if subdomain == "" {
128 return routes, subdomain
129 }
130 return subdomainRoutes, subdomain
131}
132
133func CreateServe(routes []Route, subdomainRoutes []Route, apiConfig *ApiConfig) http.HandlerFunc {
134 return func(w http.ResponseWriter, r *http.Request) {
135 curRoutes, subdomain := findRouteConfig(r, routes, subdomainRoutes, apiConfig.Cfg)
136 ctx := apiConfig.CreateCtx(r.Context(), subdomain)
137 router := CreateServeBasic(curRoutes, ctx)
138 router(w, r)
139 }
140}
141
142type ctxDBKey struct{}
143type ctxStorageKey struct{}
144type ctxLoggerKey struct{}
145type ctxCfg struct{}
146type ctxAnalyticsQueue struct{}
147
148type CtxSubdomainKey struct{}
149type ctxKey struct{}
150type CtxSshKey struct{}
151
152func GetSshCtx(r *http.Request) (ssh.Context, error) {
153 payload, ok := r.Context().Value(CtxSshKey{}).(ssh.Context)
154 if payload == nil || !ok {
155 return payload, fmt.Errorf("sshCtx not set on `r.Context()` for connection")
156 }
157 return payload, nil
158}
159
160func GetCfg(r *http.Request) *ConfigSite {
161 return r.Context().Value(ctxCfg{}).(*ConfigSite)
162}
163
164func GetLogger(r *http.Request) *slog.Logger {
165 return r.Context().Value(ctxLoggerKey{}).(*slog.Logger)
166}
167
168func GetDB(r *http.Request) db.DB {
169 return r.Context().Value(ctxDBKey{}).(db.DB)
170}
171
172func GetStorage(r *http.Request) storage.StorageServe {
173 return r.Context().Value(ctxStorageKey{}).(storage.StorageServe)
174}
175
176func GetField(r *http.Request, index int) string {
177 fields := r.Context().Value(ctxKey{}).([]string)
178 if index >= len(fields) {
179 return ""
180 }
181 return fields[index]
182}
183
184func GetSubdomain(r *http.Request) string {
185 return r.Context().Value(CtxSubdomainKey{}).(string)
186}
187
188func GetCustomDomain(host string, space string) string {
189 txt := fmt.Sprintf("_%s.%s", space, host)
190 records, err := net.LookupTXT(txt)
191 if err != nil {
192 return ""
193 }
194
195 for _, v := range records {
196 return strings.TrimSpace(v)
197 }
198
199 return ""
200}
201
202func GetAnalyticsQueue(r *http.Request) chan *db.AnalyticsVisits {
203 return r.Context().Value(ctxAnalyticsQueue{}).(chan *db.AnalyticsVisits)
204}