2016-11-22 126 views
0

这里http响应是模式:写入管读数到golang

客户端发送POST请求到服务器A

服务器A进程的这一和发送GET到服务器B

服务器B发送通过一个响应到客户端


不过,我觉得最好的办法是让这将读取的GET的响应,并写入到POST的响应管道,但我有很多类型的问题。

func main() { 
    r := mux.NewRouter() 
    r.HandleFunc("/test/{hash}", testHandler) 

    log.Fatal(http.ListenAndServe(":9095", r)) 
} 

func handleErr(err error) { 
    if err != nil { 
     log.Fatalf("%s\n", err) 
    } 
} 


func testHandler(w http.ResponseWriter, r *http.Request){ 

    fmt.Println("FIRST REQUEST RECEIVED") 
    vars := mux.Vars(r) 
    hash := vars["hash"] 
    read, write := io.Pipe() 

    // writing without a reader will deadlock so write in a goroutine 
    go func() { 
     write, _ = http.Get("http://localhost:9090/test/" + hash) 
     defer write.Close() 
    }() 

    w.Write(read) 
} 

当我运行此我得到以下错误:

./ReverseProxy.go:61:不能在参数中使用读取(键入* io.PipeReader)类型[]字节w.Write

有没有办法,以正确地插入到http响应io.PipeReader格式? 还是我以完全错误的方式做这件事?

+1

我认为你误解了一个io.Pipe的目的。为什么不直接将响应中的数据复制到ReponseWriter? (同样,一个http.Response没有Close方法,你用http.Response跟踪PipeWriter,你需要首先检查错误) – JimB

回答

3

你实际上没有写信给它,你正在替换管道的写入。

func testHandler(w http.ResponseWriter, r *http.Request) { 

    fmt.Println("FIRST REQUEST RECEIVED") 

    vars := mux.Vars(r) 
    hash := vars["hash"] 

    read, write := io.Pipe() 

    // writing without a reader will deadlock so write in a goroutine 
    go func() { 
     defer write.Close() 
     resp, err := http.Get("http://localhost:9090/test/" + hash) 
     if err != nil { 
      return 
     } 
     defer resp.Body.Close() 
     io.Copy(write, resp.Body) 

    }() 

    io.Copy(w, read) 

} 

虽然,我与@JimB同意,对于这种情况下,甚至没有必要管,这样的事情应该是更有效:

func testHandler(w http.ResponseWriter, r *http.Request) { 
    vars := mux.Vars(r) 
    hash := vars["hash"] 

    resp, err := http.Get("http://localhost:9090/test/" + hash) 
    if err != nil { 
     // handle error 
     return 
    } 
    defer resp.Body.Close() 

    io.Copy(w, resp.Body) 
} 
沿线的

东西

+2

虽然这个io.Pipe失败没有意义,这是只是一个io.Copy更多的副本。 – JimB

+1

@JimB我同意,但我想他可能会试图学习如何使用它,我会添加另一个剪辑没有它。 – OneOfOne