Support X-Forwarded-Host name for proxy

Change-Id: I50b11be093cd63217e685f6dccecad9fcdbc0898
diff --git a/Changes b/Changes
index 6369b84..814d88e 100755
--- a/Changes
+++ b/Changes
@@ -1,4 +1,5 @@
-0.38 2020-01-20
+0.38 2020-02-03
+        - Support X-Forwarded-Host name for proxy.
 
 0.37 2020-01-16
         - Removed deprecated 'kalamar_test_port' helper.
diff --git a/kalamar.conf b/kalamar.conf
index ee35197..714c32b 100644
--- a/kalamar.conf
+++ b/kalamar.conf
@@ -39,6 +39,9 @@
     ## Backend API version
     # api_version => '1.0',
 
+    ## If the application is run behind a proxy, ignore the forwarded host
+    # proxy_host => 0,
+
     ## Run the application in a subfolder behind a proxy:
     # proxy_prefix => '/korap',
 
diff --git a/lib/Kalamar.pm b/lib/Kalamar.pm
index cb8d6ab..3a60f5c 100644
--- a/lib/Kalamar.pm
+++ b/lib/Kalamar.pm
@@ -105,6 +105,24 @@
       });
   };
 
+  $conf->{proxy_host} //= 1;
+
+  # Take proxy host
+  if ($conf->{proxy_host}) {
+    $self->hook(
+      before_dispatch => sub {
+        my $c = shift;
+        if (my $host = $c->req->headers->header('X-Forwarded-Host')) {
+          foreach ($c->req->url->base) {
+            $_->host($host);
+            $_->scheme(undef);
+            $_->port(undef);
+          };
+        };
+      }
+    );
+  };
+
   # API is not yet set - define
   $conf->{api_path} //= $ENV{KALAMAR_API};
   $conf->{api_version} //= $API_VERSION;
diff --git a/t/page.t b/t/page.t
index fee1205..e04c5a7 100644
--- a/t/page.t
+++ b/t/page.t
@@ -18,6 +18,10 @@
 $c->title('Example');
 is($c->page_title, '<h2 id="page-top">Example</h2>');
 
+$t->get_ok('/' => { 'X-Forwarded-Host' => 'korap2.ids-mannheim.de'})
+  ->attr_is('meta[property="og:url"]', 'content', '//korap2.ids-mannheim.de/')
+  ;
+
 done_testing;
 
 1;