2 回答

TA貢獻1111條經驗 獲得超0個贊
正如文檔中暗示的那樣,有些人ResponseWriter可能會實現該Flusher接口。
這意味著您可以執行以下操作:
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")
}
請注意緩沖可能發生在網絡或客戶端的許多其他地方。

TA貢獻1900條經驗 獲得超5個贊
如果我誤解了您的問題,但是下面的內容可以解決問題嗎?
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¶m2=value2" http://localhost:8080
返回:
參數1=值1&參數2=值2
您可以隨時附加任何您想要的數據body,或者在再次將其全部寫出之前從其他地方將更多字節讀入緩沖區。
- 2 回答
- 0 關注
- 304 瀏覽
添加回答
舉報