go 使用net/http实现 请求通过request转发并修改响应返回

package main

import (
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
)
var BASEURL="http://gzng.boss.gmcc.net:86"

func handleRequest(w http.ResponseWriter, r *http.Request) {
	// Build the target URL
	targetURL, err := url.Parse(BASEURL + r.URL.Path)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	targetURL.RawQuery = r.URL.RawQuery

	// Create a new request using the target URL
	req, err := http.NewRequest(r.Method, targetURL.String(), r.Body)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Copy headers from original request to the new request
	for key, values := range r.Header {
		for _, value := range values {
			req.Header.Add(key, value)
		}
	}

	// Create a new HTTP client
	client := http.Client{}

	// Send the request and get the response
	resp, err := client.Do(req)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer resp.Body.Close()

	// Read the response body
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Modify the response body if needed
	modifiedBody := modifyResponseBody(body)

	// Copy headers from response to the ResponseWriter
	for key, values := range resp.Header {
		for _, value := range values {
			w.Header().Add(key, value)
		}
	}

	// Write the modified response body to the ResponseWriter
	w.WriteHeader(resp.StatusCode)
	_, err = w.Write(modifiedBody)
	if err != nil {
		log.Println(err)
	}
}

func modifyResponseBody(body []byte) []byte {
	// Modify the response body as needed
	// Here, we simply return the original response body as is
	return body
}

func main() {
	http.HandleFunc("/", handleRequest)

	err := http.ListenAndServe(":8089", nil)
	if err != nil {
		log.Fatal(err)
	}
}
搜索