代码拉取完成,页面将自动刷新
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)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。