目录
1、代码实现样例:
package main
import (
"bytes"
"encoding/json"
"io"
"log"
"net/http"
"net/http/httputil"
"net/url"
)
func main() {
// 定义反向代理的目标服务器地址
targetURL, err := url.Parse("http://localhost:8082")
if err != nil {
log.Fatalf("Failed to parse target URL: %v", err)
}
// 创建反向代理
proxy := httputil.NewSingleHostReverseProxy(targetURL)
// 修改请求处理函数
http.HandleFunc("/login", handler(proxy))
if err := http.ListenAndServe(":8887", nil); err != nil {
log.Fatalf("Failed to start proxy server: %v", err)
}
}
func handler(proxy *httputil.ReverseProxy) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Printf("Received request: %s %s", r.Method, r.URL.Path)
// 构造传入参数
params := map[string]string{
"username": "user1",
"password": "password1",
}
jsonData, err := json.Marshal(params)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Printf("Failed to marshal JSON: %v", err)
return
}
// 发送 POST 请求到目标服务器
resp, err := http.Post("http://localhost:8082/login", "application/json", bytes.NewBuffer(jsonData))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Printf("Failed to send POST request: %v", err)
return
}
defer resp.Body.Close()
// 复制响应头部
for key, values := range resp.Header {
for _, value := range values {
w.Header().Add(key, value)
}
}
// 将目标服务器的响应内容直接返回给客户端
w.WriteHeader(resp.StatusCode)
if _, err := io.Copy(w, resp.Body); err != nil {
log.Printf("Failed to write response: %v", err)
}
log.Printf("Forwarded response: %d", resp.StatusCode)
}
}