-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassets.go
More file actions
69 lines (62 loc) · 1.71 KB
/
Copy pathassets.go
File metadata and controls
69 lines (62 loc) · 1.71 KB
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
package main
import (
"net/http"
"net/http/httputil"
"net/url"
"strings"
)
func desktopAssetMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet && (r.URL.Path == "/" || r.URL.Path == "" || r.URL.Path == "/index.html") {
clone := r.Clone(r.Context())
clone.URL.Path = "/control.html"
clone.URL.RawPath = ""
next.ServeHTTP(w, clone)
return
}
next.ServeHTTP(w, r)
})
}
type assetFallbackHandler struct {
app *App
}
func (handler assetFallbackHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/codex/") {
handler.app.proxyToSidecar(w, r)
return
}
http.NotFound(w, r)
}
func (a *App) proxyToSidecar(w http.ResponseWriter, r *http.Request) {
port := a.currentPort()
if port <= 0 {
http.Error(w, "CodexPanel local service is not running.", http.StatusServiceUnavailable)
return
}
target, err := url.Parse("http://127.0.0.1:" + intString(port))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
proxy := httputil.NewSingleHostReverseProxy(target)
originalDirector := proxy.Director
proxy.Director = func(req *http.Request) {
originalDirector(req)
a.mu.Lock()
token := a.token
a.mu.Unlock()
req.Host = target.Host
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.URL.Path = r.URL.Path
req.URL.RawPath = r.URL.RawPath
req.URL.RawQuery = r.URL.RawQuery
if token != "" {
req.Header.Set("x-codex-token", token)
}
}
proxy.ErrorHandler = func(rw http.ResponseWriter, _ *http.Request, proxyErr error) {
http.Error(rw, proxyErr.Error(), http.StatusBadGateway)
}
proxy.ServeHTTP(w, r)
}