节点中实现重写规则

This commit is contained in:
GoEdgeLab
2020-09-28 18:22:37 +08:00
parent 65e6e85215
commit b6ef74d2fb
3 changed files with 76 additions and 41 deletions

View File

@@ -25,6 +25,7 @@ const (
// - http://nginx.org/en/docs/http/ngx_http_rewrite_module.html
// - https://httpd.apache.org/docs/current/mod/mod_rewrite.html
// - https://httpd.apache.org/docs/2.4/rewrite/flags.html
// TODO 实现对其他代理服务的引用
type HTTPRewriteRule struct {
Id int64 `yaml:"id" json:"id"` // ID
IsOn bool `yaml:"isOn" json:"isOn"` // 是否开启
@@ -46,20 +47,25 @@ type HTTPRewriteRule struct {
RedirectStatus int `yaml:"redirectStatus" json:"redirectStatus"` // 跳转的状态码
ProxyHost string `yaml:"proxyHost" json:"proxyHost"` // 代理模式下的Host
// TODO 实现对其他代理服务的引用
// 要替换成的URL
// 支持反向引用:${0}, ${1}, ...,也支持?P<NAME>语法
// - 如果以 proxy:// 开头表示目标为代理首先会尝试作为代理ID请求如果找不到会尝试作为代理Host请求
Replace string `yaml:"replace" json:"replace"`
IsBreak bool `yaml:"isBreak" json:"isBreak"` // 终止向下解析
// 其他选项
IsBreak bool `yaml:"isBreak" json:"isBreak"` // 终止向下解析
WithQuery bool `yaml:"withQuery" json:"withQuery"` // 是否保留QueryString
reg *regexp.Regexp
reg *regexp.Regexp
replaceHasVariables bool
proxyHostHasVariables bool
}
// 校验
func (this *HTTPRewriteRule) Init() error {
this.replaceHasVariables = configutils.HasVariables(this.Replace)
this.proxyHostHasVariables = configutils.HasVariables(this.ProxyHost)
reg, err := regexp.Compile(this.Pattern)
if err != nil {
return err
@@ -115,7 +121,9 @@ func (this *HTTPRewriteRule) Match(requestPath string, formatter func(source str
return "${" + varName + "}"
})
replace = formatter(replace)
if this.replaceHasVariables {
replace = formatter(replace)
}
return replace, varMapping, true
}
@@ -124,3 +132,8 @@ func (this *HTTPRewriteRule) Match(requestPath string, formatter func(source str
func (this *HTTPRewriteRule) IsExternalURL(url string) bool {
return shared.RegexpExternalURL.MatchString(url)
}
// 判断ProxyHost是否有变量
func (this *HTTPRewriteRule) ProxyHostHasVariables() bool {
return this.proxyHostHasVariables
}