将管道读取写入 golang 中的 http 响应

Alb*_*erk 1 http pipe go mux

这是架构:

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

服务器 A 处理这个并向服务器 B 发送一个 GET

服务器 B 通过 A 向客户端发送响应


我虽然最好的想法是制作一个管道来读取 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)
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我收到以下错误:

./ReverseProxy.go:61: 不能使用 read (type *io.PipeReader) 作为 w.Write 的参数中的 []byte 类型

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

One*_*One 8

您实际上并不是在写入它,而是在替换管道的写入。

类似的东西:

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)

}
Run Code Online (Sandbox Code Playgroud)

虽然,我同意@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)
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然这个 io.Pipe 惨败没有意义,但这只是一个带有更多副本的 io.Copy。 (3认同)
  • @JimB 我同意,但我认为他可能正在尝试学习如何使用它,我会在没有它的情况下添加另一个片段。 (2认同)