代码拉取完成,页面将自动刷新
package proxyhandler
import (
"gitee.com/captials-team/ubdframe/src/common"
"github.com/gin-gonic/gin"
"net/http"
"net/http/httputil"
"net/url"
"strings"
)
type ItfProxyMode interface {
Match(req *http.Request) bool
ServeHTTP(rw http.ResponseWriter, req *http.Request)
}
// ProxyByPrefix 根据前缀转发的代理
type ProxyByPrefix struct {
rule *ProxyRule
proxy *httputil.ReverseProxy
}
func NewProxyByPrefix(rule ProxyRule) *ProxyByPrefix {
parseRootUrl, err := url.Parse(rule.Forward)
common.ErrPanic(err)
proxy := httputil.NewSingleHostReverseProxy(parseRootUrl)
return &ProxyByPrefix{
rule: &rule,
proxy: proxy,
}
}
func (p *ProxyByPrefix) Match(req *http.Request) bool {
if strings.HasPrefix(req.URL.Path, p.rule.Match) {
return true
}
return false
}
func (p *ProxyByPrefix) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
req.URL.Path = strings.Replace(req.URL.Path, p.rule.Match, p.rule.Replace, 1)
p.proxy.ServeHTTP(rw, req)
}
// ProxyByFixed 固定匹配转发
type ProxyByFixed struct {
rule *ProxyRule
proxy *httputil.ReverseProxy
}
func NewProxyByFixed(rule ProxyRule) *ProxyByFixed {
parseRootUrl, err := url.Parse(rule.Forward)
common.ErrPanic(err)
proxy := httputil.NewSingleHostReverseProxy(parseRootUrl)
return &ProxyByFixed{
rule: &rule,
proxy: proxy,
}
}
func (p *ProxyByFixed) Match(req *http.Request) bool {
return req.URL.Path == p.rule.Match
}
func (p *ProxyByFixed) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
req.URL.Path = strings.Replace(req.URL.Path, p.rule.Match, p.rule.Replace, 1)
p.proxy.ServeHTTP(rw, req)
}
// ProxyNone 空代理
type ProxyNone struct {
}
func (p *ProxyNone) Match(req *http.Request) bool {
return false
}
func (p *ProxyNone) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
}
func NewProxy(rule ProxyRule) ItfProxyMode {
switch rule.Mode {
case ProxyModePrefix:
return NewProxyByPrefix(rule)
case ProxyModeFix:
return NewProxyByFixed(rule)
}
return &ProxyNone{}
}
func NewProxyGroup(rules ...ProxyRule) []ItfProxyMode {
var arr []ItfProxyMode
for _, v := range rules {
arr = append(arr, NewProxy(v))
}
return arr
}
func ProxyHandler(rules ...ItfProxyMode) gin.HandlerFunc {
return func(ctx *gin.Context) {
for _, v := range rules {
if v.Match(ctx.Request) {
v.ServeHTTP(ctx.Writer, ctx.Request)
ctx.Abort()
break
}
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。