|
| 1 | +# This file is part of NIT ( http://www.nitlanguage.org ). |
| 2 | +# |
| 3 | +# Copyright 2015 Philippe Pépos Petitclerc <ppeposp@gmail.com> |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +# Provides the `ProxyAction` action, which redirects requests to another interface |
| 18 | +module proxy |
| 19 | + |
| 20 | +import curl |
| 21 | +import reactor |
| 22 | + |
| 23 | +# A request proxy. All requests received by this action will be redirected to |
| 24 | +# its target. All headers are forwarded including User-Agent. |
| 25 | +# |
| 26 | +# Please note: Requests passed to this action are blocking. |
| 27 | +class ProxyAction |
| 28 | + super Action |
| 29 | + |
| 30 | + # Target interface where to dispatch proxied requests |
| 31 | + var target: Interface |
| 32 | + |
| 33 | + redef fun answer(http_request, turi) do |
| 34 | + |
| 35 | + var request = new CurlHTTPRequest("http://{self.target}{turi}") |
| 36 | + |
| 37 | + var curl_headers = new HeaderMap |
| 38 | + |
| 39 | + for k, v in http_request.header do |
| 40 | + if k == "User-Agent" then |
| 41 | + request.user_agent = v |
| 42 | + else |
| 43 | + curl_headers[k] = v |
| 44 | + end |
| 45 | + end |
| 46 | + |
| 47 | + var curl_response = request.execute |
| 48 | + var response: HttpResponse |
| 49 | + |
| 50 | + if curl_response isa CurlResponseSuccess then |
| 51 | + response = new HttpResponse(curl_response.status_code) |
| 52 | + response.body = curl_response.body_str |
| 53 | + else if curl_response isa CurlResponseFailed then |
| 54 | + response = new HttpResponse(500) |
| 55 | + |
| 56 | + # CURLE_COULDNT_RESOLVE_HOST |
| 57 | + if curl_response.error_code == 6 then |
| 58 | + response.status_code = 502 # Bad Gateway |
| 59 | + # CURLE_URL_MALFORMAT |
| 60 | + else if curl_response.error_code == 3 then |
| 61 | + response.status_code = 520 # Unknown Error |
| 62 | + # CURLE_COULDNT_CONNECT |
| 63 | + else if curl_response.error_code == 7 then |
| 64 | + response.status_code = 502 # Bad Gateway |
| 65 | + end |
| 66 | + else abort |
| 67 | + |
| 68 | + return response |
| 69 | + |
| 70 | + end |
| 71 | +end |
0 commit comments