How to use EnableFullDuplex() method in golang 1.21

88 Views Asked by At

As Golang documentation, stated, EnableFullDuplex() method on http.ResponseController permits handlers to continue to read from the request while concurrently writing the response.

I want to write a reverse proxy that sets in front of the clients and streams the requests it receives to the target server. I understand the idea behind this function, but I dont know how to use it

I do understand that httputil.NewSingleHostReverseProxy() in go stream data in intervals and send it to target server, but for learning purposes I dont want to use it and it also doesn't utilise EnableFullDuplex() any way.

This is what I did:

  1. I created an https server:
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        rc := http.NewResponseController(w)
        _ = rc.EnableFullDuplex()
        w.Write([]byte("hello"))
    })

    http.ListenAndServeTLS(":8080", "./localhost.pem", "./localhost-key.pem", nil)

And a http client sending a 2GB test file. from the server I got 2 hello message which I assume that means i got writes while client was sending the file

right?

1

There are 1 best solutions below

0
Stephen Willson On

When in full duplex mode, the application can read from the request body after the application calls the response writer WriteHeader or Write methods.

When not in full duplex mode (the default), the application cannot read data from the request body after a call to the response write WriteHeader or Write methods. The server will consume the remainder of the response body, or if the response body large, set the connection to close. Read on the request body returns an error to the application.

To enable full duplex mode, simply call the response controller EnableFullDuplex method before a call the response writer WriteHeader or Write methods.

Full duplex mode is not required to stream data between the client and the target server. The restriction when not in full duplex mode is that the entire request body must be streamed to the target server before any of the response is streamed back to the client.