在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
实现的效果: 如果访问的url路径是类似 /163/ 或 /163/debian 的形式,则转发到163开源镜像服务器
直接上代码: package main import ( "fmt" "log" "net/http" "net/http/httputil" "net/url" ) var fwdHost = "mirrors.163.com" //http首部字段的HOST取值 var fwdTo = "http://" + fwdHost + "/" var fwdPrefix = "/163/" type forward struct { RProxy *httputil.ReverseProxy } func (f *forward) ServeHTTP(wr http.ResponseWriter, req *http.Request) { //fmt.Printf("http头部是:%+v\n", req.Header) //假设这是处理http头部的代码 fmt.Printf(" #### REQ:%+v\n", req) //处理完后转发到网易163镜像 req.URL.Path = req.URL.Path[len(fwdPrefix)-1:] //修改了这里,req.RequestURI会跟着变 req.Host = fwdHost fmt.Printf(" *** REQ:%+v\n", req) f.RProxy.ServeHTTP(wr, req) } func main() { var fwd forward u, _ := url.Parse(fwdTo) fwd.RProxy = httputil.NewSingleHostReverseProxy(u) http.Handle(fwdPrefix, &fwd) //所有请求将转发到网易163的debian镜像 http.HandleFunc("/", notForward) http.HandleFunc("/api/v1/", notForward) log.Fatal(http.ListenAndServe(":3000", nil)) } func notForward(wr http.ResponseWriter, req *http.Request) { wr.Write([]byte(fmt.Sprintf(`<html> <body> <em>Not forward!!</em> <br /> <i>url = %s</i> </body> </html> `,req.URL.String()))) }
类似的还有更简单的做法,关键在httputil.ReverseProxy的Director字段: func APIReverseProxy(host string) http.HandlerFunc { var rp = httputil.ReverseProxy{ Director:func(req *http.Request) { req.URL.Scheme = "http"
关于req.URL.Host和req.Host: go http包中对request中Host的注释: // For server requests Host specifies the host on which the 另外: 对于下面的请求:
|
请发表评论