closing http request sockets

1,609 views
Skip to first unread message

Wei Tang

unread,
Oct 23, 2013, 3:49:18 PM10/23/13
to golan...@googlegroups.com
Hi I have a question about how to close an http connection explicitly? 

My program is a server providing REST API and clients calls these API using golang net.http package. 

The symptom is that I can observe in the server side /proc/<process_id>/fd directory, the socket handlers are increasing as the clients issues API calls, even the call is finished, the SOCKET fd will still be there. Thus the max limit will be reached before too long.  I checked the client side code the resp is closed after each call as follows:

esp, err := http.Get("http://example.com/")
if err != nil {
	// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// ...
My question is that if there is a way for the server to force to close the http connection to release the socket handlers?

thanks!
Wei


Message has been deleted

Specode

unread,
Oct 23, 2013, 11:56:04 PM10/23/13
to golan...@googlegroups.com
On HTTP 1.1, Any request for the client will have keep-alive, If you want to set a keep-alive timeout (server side) :
s := &http.Server{
	Addr:        ":80",
	ReadTimeout: 10 * time.Second, // this is timeout
}

log.Fatal(s.ListenAndServe())

if you want disable keep-alive:
tr := &http.Transport{
		DisableKeepAlives: true,
}
c := &http.Client{ Transport: tr }
resp, err := c.Get("https://www.google.com")

Wei Tang

unread,
Oct 24, 2013, 11:04:24 AM10/24/13
to Specode, golan...@googlegroups.com
Thanks Specod and Islan for the reply.

I tried the second option of Specod which disconnect the connection from client side, it works.

As for setting ReadTimeout, it seems not suitable for my use case where big data downloading requires a unpredictable long time.

Thanks a lot for your help!
Wei



--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/agB-n6V7UsQ/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Jared Bischof

unread,
Oct 24, 2013, 12:05:32 PM10/24/13
to golan...@googlegroups.com, Specode
For the server side, adding the following to the header of the http.ResponseWriter solved the problem for us (I'm working with Wei):

w.Header().Set("Connection", "close")

Thanks for the client-side code!
Reply all
Reply to author
Forward
Message has been deleted
0 new messages