2023-12-14 23:47:04 +08:00
|
|
|
package handler
|
2023-12-14 22:02:31 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
2023-12-14 23:47:04 +08:00
|
|
|
"net/url"
|
2023-12-14 22:02:31 +08:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/samber/lo"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ProxyRequestUpdater func(arg ...string) func(r *http.Request)
|
|
|
|
|
|
|
|
var ProxyRequestUpdateMap = map[string]ProxyRequestUpdater{
|
2023-12-14 23:47:04 +08:00
|
|
|
"HostSchemas": func(arg ...string) func(r *http.Request) {
|
|
|
|
targetUrl := arg[0]
|
2023-12-14 22:02:31 +08:00
|
|
|
return func(r *http.Request) {
|
2023-12-14 23:47:04 +08:00
|
|
|
turl, _ := url.Parse(targetUrl)
|
|
|
|
r.URL.Host = turl.Host
|
|
|
|
r.URL.Scheme = turl.Scheme
|
|
|
|
}
|
|
|
|
},
|
|
|
|
"HeaderOrigin": func(arg ...string) func(r *http.Request) {
|
|
|
|
|
|
|
|
return func(r *http.Request) {
|
|
|
|
r.Header.Set("Origin", r.URL.Scheme+"://"+r.URL.Host)
|
2023-12-14 22:02:31 +08:00
|
|
|
}
|
|
|
|
},
|
|
|
|
"Path": func(arg ...string) func(r *http.Request) {
|
|
|
|
replace := arg[0]
|
|
|
|
with := arg[1]
|
|
|
|
return func(r *http.Request) {
|
|
|
|
r.URL.Path = r.URL.Path[len(replace):]
|
2023-12-15 22:40:12 +08:00
|
|
|
r.URL.Path = strings.TrimSuffix(with, "/") + r.URL.Path
|
2023-12-14 22:02:31 +08:00
|
|
|
}
|
|
|
|
},
|
|
|
|
"RemoveCookie": func(arg ...string) func(r *http.Request) {
|
|
|
|
cookie := arg[0]
|
|
|
|
return func(r *http.Request) {
|
|
|
|
cookies := r.Cookies()
|
|
|
|
_, index, ok := lo.FindIndexOf(cookies, func(v *http.Cookie) bool {
|
|
|
|
return v.Name == cookie
|
|
|
|
})
|
|
|
|
if ok {
|
|
|
|
r.Header.Del("Cookie")
|
|
|
|
if len(cookies) == 1 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
cookies = append(cookies[:index], cookies[index+1:]...)
|
|
|
|
for _, cookie := range cookies {
|
|
|
|
r.AddCookie(cookie)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetUpdaterFn(directive string) func(r *http.Request) {
|
|
|
|
strs := strings.Split(directive, " ")
|
|
|
|
if len(strs) > 1 {
|
|
|
|
updater, ok := ProxyRequestUpdateMap[strs[0]]
|
|
|
|
if ok {
|
|
|
|
return updater(strs[1:]...)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
updater, ok := ProxyRequestUpdateMap[directive]
|
|
|
|
if ok {
|
|
|
|
return updater()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|