@@ -9,9 +9,72 @@ import (
9
9
"strings"
10
10
"time"
11
11
12
+ "github.com/RoyXiang/plexproxy/common"
12
13
"github.com/go-chi/chi/v5/middleware"
13
14
)
14
15
16
+ func newSingleHostReverseProxy (target * url.URL , hostname string ) * httputil.ReverseProxy {
17
+ targetQuery := target .RawQuery
18
+ director := func (req * http.Request ) {
19
+ req .URL .Scheme = target .Scheme
20
+ if hostname != "" {
21
+ req .URL .Host = hostname
22
+ } else {
23
+ req .URL .Host = target .Host
24
+ }
25
+ req .URL .Path , req .URL .RawPath = joinURLPath (target , req .URL )
26
+ if targetQuery == "" || req .URL .RawQuery == "" {
27
+ req .URL .RawQuery = targetQuery + req .URL .RawQuery
28
+ } else {
29
+ req .URL .RawQuery = targetQuery + "&" + req .URL .RawQuery
30
+ }
31
+ if _ , ok := req .Header ["User-Agent" ]; ! ok {
32
+ // explicitly disable User-Agent so it's not set to default value
33
+ req .Header .Set ("User-Agent" , "" )
34
+ }
35
+ }
36
+ proxy := & httputil.ReverseProxy {Director : director }
37
+
38
+ proxy .FlushInterval = - 1
39
+ proxy .ErrorLog = common .GetLogger ()
40
+ proxy .ModifyResponse = modifyResponse
41
+ proxy .ErrorHandler = proxyErrorHandler
42
+ return proxy
43
+ }
44
+
45
+ func joinURLPath (a , b * url.URL ) (path , rawpath string ) {
46
+ if a .RawPath == "" && b .RawPath == "" {
47
+ return singleJoiningSlash (a .Path , b .Path ), ""
48
+ }
49
+ // Same as singleJoiningSlash, but uses EscapedPath to determine
50
+ // whether a slash should be added
51
+ apath := a .EscapedPath ()
52
+ bpath := b .EscapedPath ()
53
+
54
+ aslash := strings .HasSuffix (apath , "/" )
55
+ bslash := strings .HasPrefix (bpath , "/" )
56
+
57
+ switch {
58
+ case aslash && bslash :
59
+ return a .Path + b .Path [1 :], apath + bpath [1 :]
60
+ case ! aslash && ! bslash :
61
+ return a .Path + "/" + b .Path , apath + "/" + bpath
62
+ }
63
+ return a .Path + b .Path , apath + bpath
64
+ }
65
+
66
+ func singleJoiningSlash (a , b string ) string {
67
+ aslash := strings .HasSuffix (a , "/" )
68
+ bslash := strings .HasPrefix (b , "/" )
69
+ switch {
70
+ case aslash && bslash :
71
+ return a + b [1 :]
72
+ case ! aslash && ! bslash :
73
+ return a + "/" + b
74
+ }
75
+ return a + b
76
+ }
77
+
15
78
func wrapResponseWriter (w http.ResponseWriter , protoMajor int ) middleware.WrapResponseWriter {
16
79
if nw , ok := w .(middleware.WrapResponseWriter ); ok {
17
80
return nw
0 commit comments