發佈時間:2020-12-21
http
import (
"log"
"github.com/valyala/fasthttp"
proxy "github.com/yeqown/fasthttp-reverse-proxy"
)
var (
// 添加要代理的 http 服務器地址
proxyServer = proxy.NewReverseProxy("localhost:8080")
// use with balancer
// weights = map[string]proxy.Weight{
// "localhost:8080": 20,
// "localhost:8081": 30,
// "localhost:8082": 50,
// }
// proxyServer = proxy.NewReverseProxy("", proxy.WithBalancer(weights))
)
// ProxyHandler ... fasthttp.RequestHandler func
func ProxyHandler(ctx *fasthttp.RequestCtx) {
// all proxy to localhost
// 調用,返回地址
proxyServer.ServeHTTP(ctx)
}
func main() {
if err := fasthttp.ListenAndServe(":8081", ProxyHandler); err != nil {
log.Fatal(err)
}
}
websocket
import (
"log"
"text/template"
"github.com/valyala/fasthttp"
proxy "github.com/yeqown/fasthttp-reverse-proxy"
)
var (
proxyServer = proxy.NewWSReverseProxy("localhost:8080", "/echo")
)
// ProxyHandler ... fasthttp.RequestHandler func
func ProxyHandler(ctx *fasthttp.RequestCtx) {
switch string(ctx.Path()) {
case "/":
proxyServer.ServeHTTP(ctx)
default:
ctx.Error("Unsupported path", fasthttp.StatusNotFound)
}
}
func main() {
if err := fasthttp.ListenAndServe(":8081", ProxyHandler); err != nil {
log.Fatal(err)
}
}