duanmiexi2275 2016-11-22 16:38
浏览 92
已采纳

在Golang中将管道读取写入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
", 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条回答 默认 最新

  • duandie0921 2016-11-22 16:51
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看