go-wasm-http-server icon indicating copy to clipboard operation
go-wasm-http-server copied to clipboard

"res.(http.Flusher).Flush()" not work

Open xiongsongsong opened this issue 2 years ago • 1 comments

when use golang direct run,it's perfect: https://user-images.githubusercontent.com/342509/128476357-3f6f97de-7f09-4b16-97b7-39571450390c.mov

package main

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

func main() {
http.HandleFunc("/wawawa",  func(res http.ResponseWriter, req *http.Request) {
	flusher := res.(http.Flusher)
	res.Header().Set("Content-Type", "text/html")
	fmt.Fprintf(res, "<!doctype html>\n<html><head><title>test</title></head><body>")
	for i := 1; i <= 50; i++ {
		fmt.Fprintf(res, "<p>Chunk #%d</p>\n<script>console.log(new Date())</script>\n", i)
		// perfect
		flusher.Flush()
		time.Sleep(500 * time.Millisecond)
	}
	fmt.Fprintf(res, "</body>\n</html>")
})

	http.ListenAndServe(":8080", nil)

	select {}
}

but with wasm, it's not work: https://user-images.githubusercontent.com/342509/128476360-f9d80484-c6e4-4bb8-805d-5fc4273727e2.mov

package main

import (
	"fmt"
	"net/http"
	"time"
	wasmhttp "github.com/nlepage/go-wasm-http-server"
)

func main() {
	http.HandleFunc("/wawawa",  func(res http.ResponseWriter, req *http.Request) {
		flusher := res.(http.Flusher)
		res.Header().Set("Content-Type", "text/html")
		fmt.Fprintf(res, "<!doctype html>\n<html><head><title>test</title></head><body>")
		for i := 1; i <= 50; i++ {
			fmt.Fprintf(res, "<p>Chunk #%d</p>\n<script>console.log(new Date())</script>\n", i)
			// not work, 25 s later
			flusher.Flush()
			time.Sleep(500 * time.Millisecond)
		}
		fmt.Fprintf(res, "</body>\n</html>")
	})

	wasmhttp.Serve(nil)

	select {}
}

xiongsongsong avatar Aug 06 '21 07:08 xiongsongsong

Hi @xiongsongsong Yes this is an expected behavior. go-wasm-http-server first records the entire response then sends it in one piece to the browser. So in your case the first 25 seconds are spent recording the response, then all the html content is sent in a whole chunk to the browser. For now this kind of response "streaming" isn't possible. There is a related issue #2, about using a ReadableStream for the response body, which should allow this kind of streaming. I'm going to try using ReadableStream, I'll keep you updated.

nlepage avatar Aug 07 '21 18:08 nlepage