proxyserver

This commit is contained in:
eson 2023-09-22 11:55:39 +08:00
parent fc50bf587f
commit e29e8d8049

View File

@ -104,18 +104,8 @@ func main() {
// 对/api开头的请求进行反向代理
proxy := httputil.NewSingleHostReverseProxy(apiURL)
// proxy.ErrorHandler = func(res http.ResponseWriter, req *http.Request, err error) {
// if err != nil {
// // 在发生错误时进行处理
// log.Println(res.Header())
// logx.Info(err)
// logx.Info(res.Header())
// res.WriteHeader(http.StatusNotFound) // 返回404状态码
// }
// }
proxy.ServeHTTP(w, r)
log.Println(w.Header())
return
} else {
@ -258,6 +248,7 @@ func NewBackend(mux *http.ServeMux, httpAddress string, muxPaths ...string) *Bac
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// defer conn.Close()
@ -270,14 +261,14 @@ func NewBackend(mux *http.ServeMux, httpAddress string, muxPaths ...string) *Bac
// 解析目标URL包含了查询参数
targetURL, err := url.Parse(httpAddress + r.URL.String())
if err != nil {
http.Error(w, "Error parsing target URL", http.StatusInternalServerError)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 创建新的请求
proxyReq, err := http.NewRequest(r.Method, targetURL.String(), r.Body)
if err != nil {
http.Error(w, "Error creating proxy request", http.StatusInternalServerError)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
@ -295,7 +286,7 @@ func NewBackend(mux *http.ServeMux, httpAddress string, muxPaths ...string) *Bac
// 发送请求
resp, err := backend.Client.Do(proxyReq)
if err != nil {
http.Error(w, "Error sending proxy request", http.StatusInternalServerError)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
@ -311,7 +302,7 @@ func NewBackend(mux *http.ServeMux, httpAddress string, muxPaths ...string) *Bac
w.WriteHeader(resp.StatusCode)
_, err = io.Copy(w, resp.Body)
if err != nil {
http.Error(w, "Error copying proxy response", http.StatusInternalServerError)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}