Skip to content

Commit d374c0e

Browse files
committed
utils: server
1 parent 29bfda3 commit d374c0e

File tree

1 file changed

+39
-24
lines changed

1 file changed

+39
-24
lines changed

src/utils/server.cr

Lines changed: 39 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -18,32 +18,47 @@
1818
# -----------------------------------------------------------------------
1919

2020
module MoonScript
21-
module Server
22-
extend self
23-
24-
def run(*, host: String = "127.0.0.1", server: HTTP::Server, port: Int32 = 3000, &callback: Proc(String, Int32, Nil))
25-
if port_closed?(host, port)
26-
if STDIN.tty?
27-
terminals.puts "#{COG} Port #{port} is already in use!"
28-
29-
while port_closed?(hsot, port)
30-
port += 1
31-
end
32-
end
33-
end
34-
end
21+
module Server
22+
extend self
3523

36-
private def port_closed?(host, port)
37-
client = Socket.tcp(Socket::Family::INET, true)
38-
client.connect(host, port, 0.25)
39-
client.close
40-
true
41-
rescue
42-
false
43-
end
24+
def run(*, host : String = "127.0.0.1", server : HTTP::Server, port : Int32 = 3000, &callback : Proc(String, Int32, Nil))
25+
if port_closed?(host, port)
26+
if STDIN.tty?
27+
terminal.puts "#{COG} Port #{port} is already in use!"
28+
29+
while port_closed?(host, port)
30+
port += 1
31+
end
4432

45-
private def terminal
46-
Render::Terminal::STDOUT
33+
terminal.puts "#{COG} Would you like to to use port #{port} instead? (Y/n)"
34+
35+
unless gets.to_s.downcase.downcase == "y"
36+
terminal.puts "#{COG} Exiting..."
37+
exit(1)
38+
end
39+
else
40+
terminal.puts "#{COG} Port #{port} is used by a different application!"
41+
exit(1)
4742
end
43+
end
44+
45+
callback.call(host, port)
46+
47+
server.bind_tcp(host, port)
48+
server.listen
49+
end
50+
51+
private def port_closed?(host, port)
52+
client = Socket.tcp(Socket::Family::INET, true)
53+
client.connect(host, port, 0.25)
54+
client.close
55+
true
56+
rescue
57+
false
58+
end
59+
60+
private def terminal
61+
Render::Terminal::STDOUT
4862
end
63+
end
4964
end

0 commit comments

Comments
 (0)