1. 程式人生 > 實用技巧 >golang 實現反向代理

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/