// Package proxy... // // Description : 正向代理的实现 // // Author : go_developer@163.com<白茶清欢> // // Date : 2021-08-06 2:07 下午 package proxy import ( "compress/gzip" "io" "io/ioutil" "net/http" "net/http/httputil" "strings" ) // Forward 正向代理的实现 // // Author : go_developer@163.com<白茶清欢> // // Date : 2:08 下午 2021/8/6 func Forward(rw http.ResponseWriter, req *http.Request, serverConfig *Server) { if !strings.HasPrefix(serverConfig.URI, "/") { serverConfig.URI = "/" + serverConfig.URI } // 请求重写方法 director := func(req *http.Request) { req.URL.Scheme = serverConfig.Scheme // req.URL.Host = projectDetail.GetProjectDetail().Domain + ":" + fmt.Sprintf("%v", projectDetail.GetProjectDetail().Port) // req.Host = projectDetail.GetProjectDetail().Domain + ":" + fmt.Sprintf("%v", projectDetail.GetProjectDetail().Port) req.Host = serverConfig.Host req.URL.Host = serverConfig.Host req.URL.Path = serverConfig.URI req.RequestURI = serverConfig.URI // 写入重写的请求Header for k, v := range serverConfig.RewriteRequestHeader { req.Header.Set(k, v) } } // TODO : 重写响应数据 modifyResponseFunc := func(rep *http.Response) error { return nil } p := &httputil.ReverseProxy{Director: director, ModifyResponse: modifyResponseFunc} p.ServeHTTP(rw, req) } // getResultCompressType 获取返回结果的压缩方式 // // Author : go_developer@163.com<白茶清欢> // // Date : 9:11 下午 2021/9/11 func getResultCompressType(res *http.Response) string { return strings.ToLower(res.Header.Get("Content-Encoding")) } // getResponseData 解析响应数据 // // Author : go_developer@163.com<白茶清欢> // // Date : 9:15 下午 2021/9/11 func getResponseData(res *http.Response) ([]byte, error) { var ( responseData []byte err error ) switch getResultCompressType(res) { case "gzip": var gzipData io.Reader if gzipData, err = gzip.NewReader(res.Body); nil == err { // gzip 处理过的数据 responseData, err = ioutil.ReadAll(gzipData) } default: // 默认没有任何压缩 responseData, err = io.ReadAll(res.Body) } return responseData, err }