Skip to content

Commit a00f655

Browse files
committed
Redirect all JSON requests to API
1 parent 8ecc6c4 commit a00f655

2 files changed

Lines changed: 39 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class JsonSubdomainRedirector
2+
def initialize(app)
3+
@api_domain = 'api.seqco.de'
4+
@api_version = 'v1'
5+
@app = app
6+
end
7+
8+
def call(env)
9+
request = Rack::Request.new(env)
10+
11+
if is_json?(request) && !already_on_api_subdomain?(request)
12+
is_versioned = request.path.match?(/^\/v\d+\//)
13+
new_path = is_versioned ? request.path : "/#{@api_version}#{request.path}"
14+
15+
# Reconstruct URL
16+
uri = URI.parse(request.url)
17+
uri.host = @api_domain
18+
uri.path = new_path
19+
20+
return [
21+
301,
22+
{ 'Location' => uri.to_s, 'Content-Type' => 'text/html' },
23+
['Moved Permanently']
24+
]
25+
end
26+
27+
@app.call(env)
28+
end
29+
30+
def is_json?(request)
31+
request.get_header('HTTP_ACCEPT')&.include?('application/json') ||
32+
request.path.end_with?('.json')
33+
end
34+
35+
def already_on_api_subdomain?(request)
36+
request.host == @api_domain
37+
end
38+
end

config/environments/production.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,4 +145,5 @@
145145
# API Configuration
146146
config.api_only = ENV['RAILS_SEQCODE_API_ONLY'].present?
147147
config.api_server = 'https://api.seqco.de/v1'
148+
config.middleware.use JsonSubdomainRedirector
148149
end

0 commit comments

Comments
 (0)