Skip to content

Commit

Permalink
Get effective host from absolute request URIs
Browse files Browse the repository at this point in the history
  • Loading branch information
gmethvin committed May 29, 2015
1 parent 6e6d21e commit 5de8000
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 7 deletions.
11 changes: 9 additions & 2 deletions framework/src/play/src/main/scala/play/api/mvc/Http.scala
Expand Up @@ -15,7 +15,7 @@ package play.api.mvc {
import scala.collection.immutable.{ TreeMap, TreeSet }
import scala.util.control.NonFatal
import scala.util.Try
import java.net.{ URLDecoder, URLEncoder }
import java.net.{ URI, URLDecoder, URLEncoder }

/**
* The HTTP request header. Note that it doesn’t contain the request body yet.
Expand Down Expand Up @@ -91,7 +91,14 @@ package play.api.mvc {
/**
* The HTTP host (domain, optionally port)
*/
lazy val host: String = headers.get(HeaderNames.HOST).getOrElse("")
lazy val host: String = {
val u = new URI(uri)
(u.getHost, u.getPort) match {
case (h, p) if h != null && p > 0 => s"$h:$p"
case (h, _) if h != null => h
case _ => headers.get(HeaderNames.HOST).getOrElse("")
}
}

/**
* The HTTP domain
Expand Down
Expand Up @@ -3,13 +3,31 @@
*/
package play.api.mvc

import java.net.URI

import org.specs2.mutable.Specification
import play.api.http.HeaderNames._
import play.api.i18n.Lang

class RequestHeaderSpec extends Specification {

"request header" should {

"handle host" in {
"relative uri with host header" in {
val rh = DummyRequestHeader("GET", "/", Headers(HOST -> "playframework.com"))
rh.host must_== "playframework.com"
}
"absolute uri" in {
val rh = DummyRequestHeader("GET", "https://example.com/test", Headers(HOST -> "playframework.com"))
rh.host must_== "example.com"
}
"absolute uri with port" in {
val rh = DummyRequestHeader("GET", "https://example.com:8080/test", Headers(HOST -> "playframework.com"))
rh.host must_== "example.com:8080"
}
}

"parse accept languages" in {

"return an empty sequence when no accept languages specified" in {
Expand Down Expand Up @@ -41,14 +59,20 @@ class RequestHeaderSpec extends Specification {
}
}

def accept(value: String) = DummyRequestHeader(Headers("Accept-Language" -> value)).acceptLanguages
def accept(value: String) = DummyRequestHeader(
headers = Headers("Accept-Language" -> value)
).acceptLanguages

case class DummyRequestHeader(headers: Headers = Headers()) extends RequestHeader {
case class DummyRequestHeader(
requestMethod: String = "GET",
requestUri: String = "/",
headers: Headers = Headers()) extends RequestHeader {
private[this] val parsedUri = new URI(requestUri)
def id = 1
def tags = Map()
def uri = ""
def path = ""
def method = ""
def uri = requestUri
def path = parsedUri.getPath
def method = requestMethod
def version = ""
def queryString = Map()
def remoteAddress = ""
Expand Down

0 comments on commit 5de8000

Please sign in to comment.