37 Star 411 Fork 76

GVPrancher/rancher

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
proxy.go 2.27 KB
一键复制 编辑 原始数据 按行查看 历史
Darren Shepherd 提交于 2018-01-12 10:38 . Fixes
package proxy
import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"regexp"
"strings"
"github.com/sirupsen/logrus"
)
const (
ForwardProto = "X-Forwarded-Proto"
APIAuth = "X-API-Auth-Header"
)
var (
httpStart = regexp.MustCompile("^http:/([^/])")
httpsStart = regexp.MustCompile("^https:/([^/])")
badHeaders = map[string]bool{
"host": true,
"transfer-encoding": true,
"content-length": true,
"x-api-auth-header": true,
}
)
type Supplier func() []string
type proxy struct {
prefix string
validHostsSupplier Supplier
}
func (p *proxy) isAllowed(host string) bool {
for _, valid := range p.validHostsSupplier() {
if valid == host {
return true
}
if strings.HasPrefix(valid, "*") && strings.HasSuffix(host, valid[1:]) {
return true
}
}
return false
}
func NewProxy(prefix string, validHosts Supplier) http.Handler {
p := proxy{
prefix: prefix,
validHostsSupplier: validHosts,
}
return &httputil.ReverseProxy{
Director: func(req *http.Request) {
if err := p.proxy(req); err != nil {
logrus.Infof("Failed to proxy %v: %v", req, err)
}
},
}
}
func (p *proxy) proxy(req *http.Request) error {
path := req.URL.String()
index := strings.Index(path, p.prefix)
destPath := path[index+len(p.prefix):]
if strings.HasPrefix(destPath, "http") {
dest := httpStart.ReplaceAll([]byte(destPath), []byte("http://$1"))
dest = httpStart.ReplaceAll(dest, []byte("https://$1"))
destPath = string(dest)
}
if !strings.HasPrefix(destPath, "http") {
destPath = "https://" + destPath
}
destURL, err := url.Parse(destPath)
if err != nil {
return err
}
destURL.RawQuery = req.URL.RawQuery
if !p.isAllowed(destURL.Host) {
return fmt.Errorf("invalid host: %v", destURL.Host)
}
headerCopy := http.Header{}
if req.TLS != nil {
headerCopy.Set(ForwardProto, "https")
}
auth := req.Header.Get(APIAuth)
if auth != "" {
headerCopy.Set("Authorization", auth)
}
for name, value := range req.Header {
if badHeaders[strings.ToLower(name)] {
continue
}
copy := make([]string, len(value))
for i := range value {
copy[i] = strings.TrimPrefix(value[i], "rancher:")
}
headerCopy[name] = copy
}
req.Host = destURL.Hostname()
req.URL = destURL
req.Header = headerCopy
return nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/rancher/rancher.git
git@gitee.com:rancher/rancher.git
rancher
rancher
rancher
v2.0.0-alpha12

搜索帮助

0d507c66 1850385 C8b1a773 1850385