升级正向代理

This commit is contained in:
白茶清欢 2021-09-11 22:38:45 +08:00
parent 014534d546
commit 71bb052bfa

View File

@ -74,18 +74,53 @@ func Forward(rw http.ResponseWriter, req *http.Request, serverConfig *Server) {
rw.Header().Set(k, v) rw.Header().Set(k, v)
} }
defer res.Body.Close()
// 重写响应数据 // 重写响应数据
if !strings.Contains(strings.ToLower(res.Header.Get("Content-Type")), "application/json") || nil == serverConfig.RewriteResponseData || len(serverConfig.RewriteResponseData) == 0 { if !strings.Contains(strings.ToLower(res.Header.Get("Content-Type")), "application/json") || nil == serverConfig.RewriteResponseData || len(serverConfig.RewriteResponseData) == 0 {
io.Copy(rw, res.Body) _, _ = io.Copy(rw, res.Body)
} else { return
var responseData []byte }
var gzipData io.Reader var (
gzipData, err = gzip.NewReader(res.Body) responseData []byte
responseData, err = ioutil.ReadAll(gzipData) )
responseData, err = getResponseData(res)
fmt.Println(string(responseData), err) fmt.Println(string(responseData), err)
bytesBuffer := bytes.NewReader([]byte(`{"data":{"permission":true}}`)) bytesBuffer := bytes.NewReader([]byte(`{"data":{"permission":true}}`))
io.Copy(rw, bytesBuffer) _, _ = io.Copy(rw, bytesBuffer)
} }
res.Body.Close()
// 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
} }