=doc first parts of HTTP model documentation

This commit is contained in:
Johannes Rudolph 2014-06-16 23:09:51 +02:00
parent d7b4770657
commit c6993dd279
7 changed files with 491 additions and 0 deletions

View file

@ -0,0 +1,86 @@
/*
* Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com>
*/
package docs.http
import akka.stream.testkit.AkkaSpec
import akka.actor.ActorSystem
import akka.util.Timeout
import scala.concurrent.duration._
import akka.http.model._
class HttpServerExampleSpec
extends AkkaSpec("akka.actor.default-mailbox.mailbox-type = akka.dispatch.UnboundedMailbox") {
def ActorSystem(): ActorSystem = system
"binding example" in {
//#bind-example
import akka.pattern.ask
import akka.io.IO
import akka.http.Http
import akka.stream.scaladsl.Flow
import akka.stream.{ MaterializerSettings, FlowMaterializer }
implicit val system = ActorSystem()
import system.dispatcher
val materializer = FlowMaterializer(MaterializerSettings())
implicit val askTimeout: Timeout = 500.millis
val bindingFuture = IO(Http) ? Http.Bind(interface = "localhost", port = 8080)
bindingFuture foreach {
case Http.ServerBinding(localAddress, connectionStream)
Flow(connectionStream).foreach {
case Http.IncomingConnection(remoteAddress, requestProducer, responseConsumer)
println("Accepted new connection from " + remoteAddress)
// handle connection here
}.consume(materializer)
}
//#bind-example
}
"full-server-example" in {
import akka.pattern.ask
import akka.io.IO
import akka.http.Http
import akka.stream.scaladsl.Flow
import akka.stream.{ MaterializerSettings, FlowMaterializer }
implicit val system = ActorSystem()
import system.dispatcher
val materializer = FlowMaterializer(MaterializerSettings())
implicit val askTimeout: Timeout = 500.millis
val bindingFuture = IO(Http) ? Http.Bind(interface = "localhost", port = 8080)
//#full-server-example
import HttpMethods._
val requestHandler: HttpRequest HttpResponse = {
case HttpRequest(GET, Uri.Path("/"), _, _, _)
HttpResponse(
entity = HttpEntity(MediaTypes.`text/html`,
<html><body>Hello world!</body></html>.toString))
case HttpRequest(GET, Uri.Path("/ping"), _, _, _) HttpResponse(entity = "PONG!")
case HttpRequest(GET, Uri.Path("/crash"), _, _, _) sys.error("BOOM!")
case _: HttpRequest HttpResponse(404, entity = "Unknown resource!")
}
// ...
bindingFuture foreach {
case Http.ServerBinding(localAddress, connectionStream)
Flow(connectionStream).foreach {
case Http.IncomingConnection(remoteAddress, requestProducer, responseConsumer)
println("Accepted new connection from " + remoteAddress)
Flow(requestProducer).map(requestHandler).produceTo(materializer, responseConsumer)
}.consume(materializer)
}
//#full-server-example
}
}

View file

@ -0,0 +1,85 @@
package docs.http
//#import-model
import akka.http.model._
import org.scalatest.MustMatchers
//#import-model
import akka.stream.testkit.AkkaSpec
import akka.util.ByteString
import akka.http.model.headers.{ GenericHttpCredentials, BasicHttpCredentials }
class ModelSpec extends AkkaSpec {
"construct request" in {
//#construct-request
import HttpMethods._
// construct simple GET request to `homeUri`
val homeUri = Uri("/abc")
HttpRequest(GET, uri = homeUri)
// construct simple GET request to "/index" which is converted to Uri automatically
HttpRequest(GET, uri = "/index")
// construct simple POST request containing entity
val data = ByteString("abc")
HttpRequest(POST, uri = "/receive", entity = data)
// customize every detail of HTTP request
import HttpProtocols._
import MediaTypes._
val userData = ByteString("abc")
val authorization = headers.Authorization(BasicHttpCredentials("user", "pass"))
HttpRequest(
PUT,
uri = "/user",
entity = HttpEntity(`text/plain`, userData),
headers = List(authorization),
protocol = `HTTP/1.0`)
//#construct-request
}
"construct response" in {
//#construct-response
import StatusCodes._
// simple OK response without data created using the integer status code
HttpResponse(200)
// 404 response created using the named StatusCode constant
HttpResponse(NotFound)
// 404 response with a body explaining the error
HttpResponse(404, entity = "Unfortunately, the resource couldn't be found.")
// A redirecting response containing an extra header
val locationHeader = headers.Location("http://example.com/other")
HttpResponse(Found, headers = List(locationHeader))
//#construct-response
}
"deal with headers" in {
//#headers
import akka.http.model.headers._
// create a ``Location`` header
val loc = Location("http://example.com/other")
// create an ``Authorization`` header with HTTP Basic authentication data
val auth = Authorization(BasicHttpCredentials("joe", "josepp"))
// a method that extracts basic HTTP credentials from a request
case class User(name: String, pass: String)
def credentialsOfRequest(req: HttpRequest): Option[User] =
for {
Authorization(BasicHttpCredentials(user, pass)) <- req.header[headers.Authorization]
} yield User(user, pass)
//#headers
credentialsOfRequest(HttpRequest(headers = List(auth))) should be(Some(User("joe", "josepp")))
credentialsOfRequest(HttpRequest()) should be(None)
credentialsOfRequest(HttpRequest(headers = List(Authorization(GenericHttpCredentials("Other", Map.empty[String, String]))))) should be(None)
}
}