This repository has been archived by the owner on Nov 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.rb
88 lines (77 loc) · 1.96 KB
/
app.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
83
84
85
86
87
88
require 'sinatra/base'
require 'sprockets'
require 'json'
require 'securerandom'
require 'uri'
require 'yaml'
require 'dotenv/load'
require_relative 'services/url_service'
CONFIGURATION = YAML.load_file('config.yml')
class App < Sinatra::Base
set :url, CONFIGURATION['url']
set :short_path_length, CONFIGURATION['short_path_length']
set :environment, Sprockets::Environment.new
environment.append_path("assets/stylesheets")
environment.append_path("assets/javascripts")
# Allow Docker bindings
set :bind, '0.0.0.0'
get '/' do
erb :index
end
post '/shorten', provides: :json do
begin
pass unless request.accept? 'application/json'
body = request.body.read
long_url = JSON.parse(body)['url']
long_url = "http://#{long_url}" unless long_url.start_with? 'http'
# Check URL validity
URI.parse(long_url)
# Create short link
url_service = UrlService.new
short_path = url_service.create(long_url, settings.short_path_length)
short_url = "http://#{settings.url}/#{short_path}"
res = {
url: {
long: long_url,
short: short_url
}
}.to_json
[200, {}, res]
rescue URI::InvalidURIError # bad url
res = {
error: {
url: "#{params[:url]}",
message: 'The format of this url appears invalid.'
}
}.to_json
[400, {}, res]
rescue JSON::ParserError # bad json
res = {
error: {
body: "#{body}",
message: 'The body passed is not valid JSON.'
}
}.to_json
[400, {}, res]
end
end
get '/terms' do
erb :terms
end
get '/privacy' do
erb :privacy
end
get "/assets/*" do
env["PATH_INFO"].sub!("/assets", "")
settings.environment.call(env)
end
get '/:short_path' do
url_service = UrlService.new
long_url = url_service.read(params[:short_path])
if long_url.nil?
halt 404
else
redirect long_url
end
end
end