forked from tensaix2j/cryptotickers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcryptohttpd.tcl
149 lines (99 loc) · 2.39 KB
/
cryptohttpd.tcl
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#-----------
proc on_error { sock err } {
puts "$sock:$err"
}
#-----------
proc on_data { sock msg } {
puts "$sock:$msg"
foreach { action path protocol } $msg {
puts "ACTION: $action"
puts "PATH: $path"
puts "PROTOCOL: $protocol"
puts $sock "HTTP/1.0 200 OK"
if { [ file extension $path ] == ".css" } {
puts $sock "Content-Type: text/css"
} else {
puts $sock "Content-Type: text/html"
}
puts $sock ""
if { [ catch {
# Take out the dangerous stuffs like ".." just in case...
set path [ string map {.. {}} $path ]
if { $path == "/cryptotickers.json" } {
# Dynamic content
source "cryptotickers.tcl"
response $sock
} elseif { [ string match "/cryptotickers.*" $path ] || $path == "/" || [ string match "/index*" $path ] || [ string match "*.json" $path ] } {
# Static content
set filename [ file tail [ file normalize $path ] ]
puts "|$filename|"
if { $filename == "" || [ string match index* $filename ] } {
set filename "cryptotickers.html"
}
set fullpath "./public/$filename"
if { ![ file exists $fullpath ] } {
puts $sock "{}"
}
if { [ file exists $fullpath ] } {
set fp [ open $fullpath ]
set content [ read $fp ]
close $fp
puts $sock $content
}
} else {
puts $sock "Nope. Nothing there.."
}
} err ] } {
set errmsg "Error occured. $err"
puts $sock $errmsg
puts $errmsg
}
close $sock
puts "\n\n"
break
}
}
#-----------
proc on_close { sock } {
puts "$sock closed"
}
#-----------
proc on_readable { sock } {
if { [ catch { set input [gets $sock] } err ] } {
on_error $sock $err
}
if { [eof $sock] } {
on_close $sock
close $sock
} else {
on_data $sock $input
}
}
#-----------
proc on_connected { sock addr port } {
fileevent $sock readable [list on_readable $sock ]
fconfigure $sock -translation auto -buffering line
}
#---------------------------
proc do_cron { } {
get_rate
after $::config(-cron_interval) ::do_cron
}
#----------------
array set ::config {
-port 10000
-cron_interval 60000
}
#-----------
proc main { argc argv } {
array set ::config $argv
if { [ info exists ::config(-p) ] } {
set ::config(-port) $::config(-p)
}
socket -server on_connected $::config(-port)
puts "Server started at port $::config(-port)"
source "cryptocron.tcl"
do_cron
vwait forever
}
main $argc $argv