Title is say. I need only status code. Not response body.
package main
import (
"fmt"
"net/http"
)
func main() {
req, _ := http.NewRequest("POST", "http://api.example.com/getUserList", nil)
res, _ := http.DefaultClient.Do(req) // <-- 300KB Full page downloading here
fmt.Print("status code", res.StatusCode)
}
How can i interrupt response stream after got status code? (or its possible?)
Thanks
The short answer is... it's probably not possible.
Generally speaking, an HTTP client will always retrieve the full response (status, headers, and body) for any response that includes a body since that is just how HTTP works. Note that the "HEAD" method specifically does what you want but since you must use the "POST" method it obviously doesn't apply here.
As commenters have mentioned, in some sense you can simply ignore the response body by not reading it (as your current example does) but the client system will still incur the network cost of downloading the body - it just won't surface in your application.
It's theoretically possible that you could implement a custom HTTP client (or perhaps configure an existing client) so that it attempts to terminate the underlying TCP connection as soon as the HTTP status is retrieved and ignores the remainder of the HTTP response; however, this strategy is likely very complicated and would be subject to a large number of factors that might be out of control of the application.
Ultimately, your example code is probably the best you can do to pay attention only to the status code and ignore the response body. It might be worth closing the response reader immediately to indicate to the HTTP library that the associated resources are not needed and can be freed immediately; however, there's no guarantee that it would have any effect. Moreover, you might be able to configure the HTTP client to use a very small buffer for the response body in an attempt to minimize the resources used before closing the body, but again, probably no guarantee that this would actually prevent the response body from being sent over the network.