golang 实现反向代理

golang 实现反向代理

httputil中的实现

package main

import(
        "log"
        "net/url"
        "net/http"
        "net/http/httputil"
)

func main() {
        remote, err := url.Parse("http://google.com")
        if err != nil {
                panic(err)
        }

        proxy := httputil.NewSingleHostReverseProxy(remote)
        http.HandleFunc("/", handler(proxy))
        err = http.ListenAndServe(":8080", nil)
        if err != nil {
                panic(err)
        }
}

func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
        return func(w http.ResponseWriter, r *http.Request) {
                log.Println(r.URL)
                w.Header().Set("X-Ben", "Rad")
                p.ServeHTTP(w, r)
        }
}

echo框架的实现

e := echo.New()
proxy := httputil.NewSingleHostReverseProxy(&url.URL{
    Scheme: "http",
    Host:   "localhost:8081",
})
e.Any("/users", echo.WrapHandler(proxy))
e.Start(":8080")

相关链接

https://www.integralist.co.uk/posts/golang-reverse-proxy/
https://lihaoquan.me/2018/4/24/go-reverse-proxy.html
https://echo.labstack.com/cookbook/reverse-proxy
https://www.itfanr.cc/2017/06/15/Golang-implements-HTTP-request-and-proxy-settings/

原文地址:https://www.cnblogs.com/tomtellyou/p/14185709.html