Not buffered http.ResponseWritter in Golang

冷暖自知 提交于 2019-11-28 04:40:50

As implied in the documentation, some ResponseWriter may implement the Flusher interface.

This means you can do something like this :

func handle(res http.ResponseWriter, req *http.Request) {
  fmt.Fprintf(res, "sending first line of data")
  if f, ok := res.(http.Flusher); ok {
     f.Flush()
  } else {
     log.Println("Damn, no flush");
  }
  sleep(10) //not real code
  fmt.Fprintf(res, "sending second line of data")
}

Be careful that buffering can occur in many other places in the network or client side.

Sorry if I've misunderstood your question, but would something like the below do the trick?

package main

import (
    "bytes"
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    body := make([]byte, int(r.ContentLength))
    b := bytes.NewBuffer(body)
    if _, err := b.ReadFrom(r.Body); err != nil {
        fmt.Fprintf(w, "%s", err)
    }
    if _, err := b.WriteTo(w); err != nil {
        fmt.Fprintf(w, "%s", err)
    }
}

func main() {
    http.HandleFunc("/", handler)
    if err := http.ListenAndServe(":8080", nil); err != nil {
        panic(err)
    }
}

$ curl --data "param1=value1&param2=value2" http://localhost:8080

returns:

param1=value1&param2=value2

You could always append whatever data you wanted to body, or read more bytes into the buffer from elsewhere before writing it all out again.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!