http内网转发
package main import ( "io" "log" "net/http" "strings" ) func main() { localHost := "127.0.0.1.8001" targetHost := "127.0.0.1:80" httpsServer(localHost, targetHost) log.Fatalln("http server down!!!") } func httpsServer(addr string, remote_addr string) { http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { cli := &http.Client{} body := make([]byte, 0) n, err := io.ReadFull(req.Body, body) if err != nil { io.WriteString(w, "Request Data Error") return } reqUrl := "http://" + remote_addr + req.URL.Path req2, err := http.NewRequest(req.Method, reqUrl, strings.NewReader(string(body))) if err != nil { io.WriteString(w, "Request Error") return } // set request content type contentType := req.Header.Get("Content-Type") req2.Header.Set("Content-Type", contentType) // request rep2, err := cli.Do(req2) if err != nil { io.WriteString(w, "Not Found!") return } defer rep2.Body.Close() n, err = io.ReadFull(rep2.Body, body) if err != nil { io.WriteString(w, "Request Error") return } // set response header for k, v := range rep2.Header { w.Header().Set(k, v[0]) } io.WriteString(w, string(body[:n])) }) var err error = nil err = http.ListenAndServe(":12307", nil) if err != nil { log.Fatal("server down!!!") } }