redirect • Akka HTTP (original) (raw)
Signature
def redirect(uri: Uri, redirectionType: Redirection): StandardRoute
Description
Completes the request with a redirection response to a given target URI and of a given redirection type (status code).
redirect
is a convenience helper for completing the request with a redirection response. It is equivalent to this snippet relying on the complete
method on RequestContextRequestContext, and a directive is also available:
Scala
sourcecomplete(HttpResponse( status = redirectionType, headers = headers.Location(uri) :: Nil, entity = redirectionType.htmlTemplate match { case "" => HttpEntity.Empty case template => HttpEntity(ContentTypes.`text/html(UTF-8)`, template format uri) }))
Java
sourcerc.completeWith(HttpResponse.create() .withStatus(redirectionType) .addHeader(Location.create(uri))
Example
Scala
source`val route = pathPrefix("foo") { concat( pathSingleSlash { complete("yes") }, pathEnd { redirect("/foo/", StatusCodes.PermanentRedirect) } ) }
// tests: Get("/foo/") ~> route ~> check { responseAs[String] shouldEqual "yes" }
Get("/foo") ~> route ~> check { status shouldEqual StatusCodes.PermanentRedirect responseAs[String] shouldEqual """The request, and all future requests should be repeated using this URI.""" }`
Java
source`import static akka.http.javadsl.server.Directives.complete; import static akka.http.javadsl.server.Directives.pathEnd; import static akka.http.javadsl.server.Directives.pathPrefix; import static akka.http.javadsl.server.Directives.pathSingleSlash; import static akka.http.javadsl.server.Directives.redirect; final Route route = pathPrefix("foo", () -> concat( pathSingleSlash(() -> complete("yes")), pathEnd(() -> redirect(Uri.create("/foo/"), StatusCodes.PERMANENT_REDIRECT)) ) );
// tests: testRoute(route).run(HttpRequest.GET("/foo/")) .assertEntity("yes");
testRoute(route).run(HttpRequest.GET("/foo")) .assertStatusCode(StatusCodes.PERMANENT_REDIRECT) .assertEntity("The request, and all future requests should be repeated using <a href="/foo/">this URI.");`
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.