forked from brentley/ecsdemo-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapplication_controller.rb
107 lines (89 loc) · 2.58 KB
/
application_controller.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
require 'net/http'
require 'resolv'
require 'uri'
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
# Example endpoint that calls the backend nodejs api
def index
begin
req = Net::HTTP::Get.new(nodejs_uri.to_s)
res = Net::HTTP.start(nodejs_uri.host, nodejs_uri.port) {|http|
http.read_timeout = 2
http.open_timeout = 2
http.request(req)
}
if res.code == '200'
@text = res.body
else
@text = "no backend found"
end
rescue => e
logger.error e.message
logger.error e.backtrace.join("\n")
@text = "no backend found"
end
begin
crystalreq = Net::HTTP::Get.new(crystal_uri.to_s)
crystalres = Net::HTTP.start(crystal_uri.host, crystal_uri.port) {|http|
http.read_timeout = 2
http.open_timeout = 2
http.request(crystalreq)
}
if crystalres.code == '200'
@crystal = crystalres.body
else
@crystal = "no backend found"
end
rescue => e
logger.error e.message
logger.error e.backtrace.join("\n")
@crystal = "no backend found"
end
end
# This endpoint is used for health checks. It should return a 200 OK when the app is up and ready to serve requests.
def health
render plain: "OK"
end
def crystal_uri
expand_url ENV["CRYSTAL_URL"]
end
def nodejs_uri
expand_url ENV["NODEJS_URL"]
end
# Resolve the SRV records for the hostname in the URL
def expand_url(url)
uri = URI(url)
resolver = Resolv::DNS.new()
# if host is relative, append the service discovery name
host = uri.host.count('.') > 0 ? uri.host : "#{uri.host}.#{ENV["_SERVICE_DISCOVERY_NAME"]}"
# lookup the SRV record and use if found
begin
srv = resolver.getresource(host, Resolv::DNS::Resource::IN::SRV)
uri.host = srv.target.to_s
uri.port = srv.port.to_s
logger.info "uri port is #{uri.port}"
if uri.port == 0
uri.port = 80
logger.info "uri port is now #{uri.port}"
end
rescue => e
logger.error e.message
logger.error e.backtrace.join("\n")
end
logger.info "expanded #{url} to #{uri}"
uri
end
before_action :discover_availability_zone
before_action :code_hash
def discover_availability_zone
@az = ENV["AZ"]
end
def code_hash
@code_hash = ENV["CODE_HASH"]
end
def custom_header
response.headers['Cache-Control'] = 'max-age=86400, public'
end
end