Write pipe reading into http response in golang

huangapple go评论78阅读模式
英文:

Write pipe reading into http response in golang

问题

以下是翻译好的内容:

这是架构:

客户端发送一个POST请求给服务器A

服务器A处理请求并发送一个GET请求给服务器B

服务器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()

    // 在没有读取器的情况下进行写入会导致死锁,因此在goroutine中进行写入
    go func() {
        write, _ = http.Get("http://localhost:9090/test/" + hash)
        defer write.Close()
    }()

    w.Write(read)
}

当我运行这段代码时,我得到以下错误:

./ReverseProxy.go:61: cannot use read (type *io.PipeReader) as type []byte in argument to w.Write

有没有办法将io.PipeReader格式正确地插入到http响应中?
或者我完全错了吗?

英文:

Here is the schema :

Client sends a POST request to server A

server A process this and sends a GET to server B

server B sends a response through A to the client


I though the best idea was to make a pipe which would read the response of the GET, and write into the response of the POST, but I got many types problems.

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)
}

When I run this I get the following error:

./ReverseProxy.go:61: cannot use read (type *io.PipeReader) as type []byte in argument to w.Write

Is there a way, to properly insert a io.PipeReader format into an http response?
Or am I doing this in a totally wrong way?

答案1

得分: 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()

    // 在没有读取器的情况下进行写入会导致死锁,因此在 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 的观点对于这种情况甚至不需要使用管道像这样的代码应该更高效

```go
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 {
        // 处理错误
        return
    }
    defer resp.Body.Close()

    io.Copy(w, resp.Body)
}
英文:

You are not actually writing to it, you're replacing the pipe's write.

Something along the lines of:

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)

}

Although, I agree with @JimB, for this instance, the pipe isn't even needed, something like this should be more efficient:

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)
}

huangapple
  • 本文由 发表于 2016年11月23日 00:38:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/40747152.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定