-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhttp_tools-1.0.3.tm
86 lines (82 loc) · 2.07 KB
/
http_tools-1.0.3.tm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package require http
if { ! [catch { package require tls }] } {
proc ::http::_ssl_configure args {
set opts [lrange $args 0 end-2]
set host [lindex $args end-1]
set port [lindex $args end]
::tls::socket \
-ssl3 0 \
-ssl2 0 \
-tls1 1 \
-servername $host \
{*}$opts $host $port
}
::http::register https 443 ::http::_ssl_configure
}
proc ::http::_followRedirects {url args} {
while 1 {
set token [::http::geturl $url -validate 1]
set ncode [::http::ncode $token]
if { $ncode eq "404" } {
throw error "URL Not found"
}
switch -glob -- $ncode {
30[1237] {### redirect - see below ###}
default {::http::cleanup $token ; return $url}
}
upvar #0 $token state
array set meta [set ${token}(meta)]
::http::cleanup $token
if {![info exists meta(Location)]} {
return $url
}
set url $meta(Location)
unset meta
}
return $url
}
# taken from undocumented tcllib module
# with some modifications.
proc ::wget { url dest {retry 1} } {
try {
set chan [open $dest w]
chan configure $chan -translation binary
set url [::http::_followRedirects $url]
set token [::http::geturl $url -channel $chan -binary 1]
if { [::http::ncode $token] != "200" } {
::http::cleanup $token
if { $retry > 0 } {
after 500
tailcall ::wget $url $dest [incr retry -1]
}
return 0
}
::http::cleanup $token
chan close $chan
} on error {result} {
if { [info exists token] } {
::http::cleanup $token
}
if { $retry > 0 } {
after 500
tailcall ::wget $url $dest [incr retry -1]
}
}
return 1
}
proc ::http::parse_token { token } {
try {
set response [dict create \
code [::http::ncode $token] \
status [::http::status $token] \
data [::http::data $token]
]
} on error {result options} {
if {[info commands ::onError] ne {}} {
catch { ::onError $result $options "While Parsing a Token" }
}
} finally {
catch { ::http::cleanup $token }
return $response
}
}