diff --git a/examples/index.php b/examples/index.php index a60543f..f79ae1a 100644 --- a/examples/index.php +++ b/examples/index.php @@ -86,6 +86,12 @@ $app->use(function ($c, $next) { return $next($c); }); +$app->get("/redirect", function ($c) { + $message = $c->get("message"); + + return $c->redirect("/greet/hello?name=jamie", 301); +}); + $app->get("/", function ($c) { $message = $c->get("message"); diff --git a/src/Context.php b/src/Context.php index 35fdf14..428cbb3 100644 --- a/src/Context.php +++ b/src/Context.php @@ -64,4 +64,9 @@ class Context { return isset($this->variables[$key]); } + + public function redirect($url, $status = 302) + { + return $this->res->redirect($url, $status); + } } diff --git a/src/Dumbo.php b/src/Dumbo.php index 76164a9..93a6985 100644 --- a/src/Dumbo.php +++ b/src/Dumbo.php @@ -90,13 +90,13 @@ class Dumbo $this->server->sendResponse( $response->getStatusCode(), $response->getHeaders(), - $response->getBody() + $response->getBody() ?? "" ); } elseif ($response !== null) { $this->server->sendResponse( 200, ["Content-Type" => "text/plain"], - $response + (string) $response ); } else { $this->server->sendResponse(204, [], ""); diff --git a/src/Response.php b/src/Response.php index 40e47ab..a0bac90 100644 --- a/src/Response.php +++ b/src/Response.php @@ -60,4 +60,12 @@ class Response { return $this->body; } + + public function redirect($url, $status = 302) + { + $this->statusCode = $status; + $this->header("Location", $url); + + return $this; + } }