-
Notifications
You must be signed in to change notification settings - Fork 2
/
myurls.rb
82 lines (71 loc) · 1.74 KB
/
myurls.rb
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
# encoding: UTF-8
module Myurls
class App < Sinatra::Base
register Sinatra::ActiveRecordExtension
set :show_exceptions, :after_handler
configure :production, :development do
enable :logging
end
configure :production do
set :database, {adapter: "sqlite3", database: "db/production.sqlite3"}
end
configure :development do
register Sinatra::Reloader
set :database, {adapter: "sqlite3", database: "db/development.sqlite3"}
end
configure :test do
register Sinatra::Reloader
set :database, {adapter: "sqlite3", database: "db/test.sqlite3"}
end
get '/' do
@url = request.host
unless request.port == 80 || request.port == 443
@url += ":#{request.port}"
end
haml :url
end
post '/url' do
url = @params[:url]
logger.info url
if url.nil? || url.empty?
status 400
body 'Invalid url'
return
end
unless url =~ URI.regexp
status 400
body 'Invalid url'
return
end
logger.info URI.parse(url).host
logger.info request.host
if URI.parse(url).host == request.host
status 400
body 'Invalid url'
return
end
now = DateTime.now
new_url = Urls.new
new_url.url = url
new_url.short = Myurls::Utils.shorten url, now.to_s
new_url.created_at = now
new_url.save!
new_url.short
end
get '/signin' do
haml :signin
end
get '/signup' do
haml :signup
end
get '/:url' do
logger.info "-----> #{params[:url]}"
url = Urls.find_by_short(params[:url])
if url.nil? or url.url.empty?
halt 404
else
redirect url.url, 301
end
end
end
end