Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Do I need to cleanup the http token

44 views
Skip to first unread message

Cecil Westerhof

unread,
Jun 6, 2018, 2:28:04 AM6/6/18
to
I defined the following proc:
proc getExternalIP {} {
return [string trim [http::data [http::geturl http://myexternalip.com/raw]]]
}

Is this OK, or do I need to cleanup the token that is generated by
http::data?

--
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof

heinrichmartin

unread,
Jun 6, 2018, 3:08:02 AM6/6/18
to
On Wednesday, June 6, 2018 at 8:28:04 AM UTC+2, Cecil Westerhof wrote:
> Is this OK, or do I need to cleanup the token that is generated by
> http::data?

"[...] It is strongly recommended that you call this function after you are done with a given HTTP request. Not doing so will result in memory not being freed, and if your app calls ::http::geturl enough times, the memory leak could cause a performance hit...or worse." (https://tcl.tk/man/tcl8.6/TclCmd/http.htm#M43)

Cecil Westerhof

unread,
Jun 6, 2018, 4:44:05 AM6/6/18
to
Thanks. I have it rewritten to:
proc getExternalIP {} {
set token [http::geturl http://myexternalip.com/raw]
set externalIP [string trim [http::data ${token}]]
::http::cleanup ${token}
return ${externalIP}

heinrichmartin

unread,
Jun 6, 2018, 5:20:52 AM6/6/18
to
On Wednesday, June 6, 2018 at 10:44:05 AM UTC+2, Cecil Westerhof wrote:
> proc getExternalIP {} {
> set token [http::geturl http://myexternalip.com/raw]
> set externalIP [string trim [http::data ${token}]]
> ::http::cleanup ${token}
> return ${externalIP}
> }

It might be overkill in this case, but you seem to like learning features of Tcl:

proc insecureGetExternalIp {} {
set token [::http::geturl http://myexternalip.com/raw]
try {
string trim [::http::data $token]
} finally {
::http::cleanup $token
}
}

Notes:
* Considering variable context only, [set token] might go inside [try]; but if [::http::geturl] failed, then token is not defined in finally. This would hide the original error in the key -during of the result dict.
* I removed the [return] to demonstrate how the return value of commands propagate in this case. However, iirc "it is always a good idea to use [return] explicitly" (reference or correction needed as I cannot recall the reason).

Mike Griffiths

unread,
Jun 6, 2018, 4:40:54 PM6/6/18
to
If memory serves, part of the reason for always including 'return' was that it byte-compiled better and improved overall performance, though I am fairly certain that this is no longer the case.

I've never used [try] myself (I was only vaguely aware of its having been added), and would have assumed the return value would come from the 'finally' script - thanks for demonstrating!
0 new messages