37 Star 411 Fork 76

GVPrancher/rancher

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
main.go 2.29 KB
一键复制 编辑 原始数据 按行查看 历史
package main
import (
"flag"
"fmt"
"io"
"net/http"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/mux"
"github.com/rancher/rancher/pkg/remotedialer"
"github.com/sirupsen/logrus"
)
var (
addr string
clients = map[string]*http.Client{}
l sync.Mutex
counter int64
)
func authorizer(req *http.Request) (string, bool, error) {
id := req.Header.Get("x-tunnel-id")
return id, id != "", nil
}
func onError(rw http.ResponseWriter, _ *http.Request, code int, err error) {
rw.WriteHeader(code)
rw.Write([]byte(err.Error()))
}
func ready() bool {
return true
}
func Client(server *remotedialer.Server, rw http.ResponseWriter, req *http.Request) {
timeout := req.URL.Query().Get("timeout")
if timeout == "" {
timeout = "15"
}
vars := mux.Vars(req)
clientKey := vars["id"]
url := fmt.Sprintf("%s://%s%s", vars["scheme"], vars["host"], vars["path"])
client := getClient(server, clientKey, timeout)
id := atomic.AddInt64(&counter, 1)
logrus.Infof("[%03d] REQ t=%s %s", id, timeout, url)
resp, err := client.Get(url)
if err != nil {
logrus.Errorf("[%03d] REQ ERR t=%s %s: %v", id, timeout, url, err)
onError(rw, req, 500, err)
return
}
defer resp.Body.Close()
logrus.Infof("[%03d] REQ OK t=%s %s", id, timeout, url)
rw.WriteHeader(resp.StatusCode)
io.Copy(rw, resp.Body)
logrus.Infof("[%03d] REQ DONE t=%s %s", id, timeout, url)
}
func getClient(server *remotedialer.Server, clientKey, timeout string) *http.Client {
l.Lock()
defer l.Unlock()
key := fmt.Sprintf("%s/%s", clientKey, timeout)
client := clients[key]
if client != nil {
return client
}
dialer := server.Dialer(clientKey, 15*time.Second)
client = &http.Client{
Transport: &http.Transport{
Dial: dialer,
},
}
if timeout != "" {
t, err := strconv.Atoi(timeout)
if err == nil {
client.Timeout = time.Duration(t) * time.Second
}
}
clients[key] = client
return client
}
func main() {
flag.StringVar(&addr, "listen", ":8123", "Listen address")
flag.Parse()
handler := remotedialer.New(authorizer, onError, ready)
router := mux.NewRouter()
router.Handle("/connect", handler)
router.HandleFunc("/client/{id}/{scheme}/{host}{path:.*}", func(rw http.ResponseWriter, req *http.Request) {
Client(handler, rw, req)
})
fmt.Println("Listening on ", addr)
http.ListenAndServe(addr, router)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/rancher/rancher.git
git@gitee.com:rancher/rancher.git
rancher
rancher
rancher
v2.0.2

搜索帮助

0d507c66 1850385 C8b1a773 1850385