$emails->post('/', 'addEmailAddress'); $emails->put('/{code}/{email}', 'updateEmailAddress'); $emails->get('/{code}/{email}', 'getEmailAddress'); $app->mount($emails); /** * Expose the /v1/orders end point */ $orders = new MicroCollection(); $orders->setHandler('OrderController', true); $orders->setPrefix('/v1/orders'); $orders->post('/', 'addOrder'); $orders->post('/quote', 'getQuote'); $app->mount($orders); /** * CORS Headers to allow the web app to communicate with the web service */ $app->response->setHeader('Access-Control-Allow-Origin', '*'); /** * Not found handler */ $app->notFound(function () use($app) { $app->response->setStatusCode(404, HttpStatusCodes::getMessage(404))->sendHeaders(); $app->response->setContentType('application/json'); $app->response->setJsonContent(['status' => 'error', 'message' => ResponseMessages::METHOD_NOT_IMPLEMENTED, 'code' => 'METHOD_NOT_IMPLEMENTED']); $app->response->send(); }); $app->handle(); } catch (\Exception $e) { $app->response->setStatusCode(500, HttpStatusCodes::getMessage(500))->sendHeaders(); echo json_encode(['status' => 'error', 'message' => ResponseMessages::INTERNAL_SERVER_ERROR, 'code' => 'INTERNAL_SERVER_ERROR', 'ex' => $e->getMessage()]); }
$onlytestnet = ""; } $sql = sprintf("UPDATE cmd_nodes SET VersionID=%d WHERE KeepUpToDate=1{$onlytestnet}", $versionid); if ($result = $mysqli->query($sql)) { $info2 = $mysqli->info; if (is_null($info2)) { $info2 = true; } } else { $info2 = $mysqli->errno . ': ' . $mysqli->error; } //Change the HTTP status $response->setStatusCode(202, "Accepted"); $response->setJsonContent(array('status' => 'OK', 'data' => array('VersionId' => $versionid, "KeepUpToDate" => $info2))); } else { $response->setStatusCode(503, "Service Unavailable"); $response->setJsonContent(array('status' => 'ERROR', 'messages' => array($mysqli->errno . ': ' . $mysqli->error))); } } return $response; }); // ============================================================================ // End-point not found // ============================================================================ $app->notFound(function () use($app) { $response = new Phalcon\Http\Response(); $response->setStatusCode(404, "Not Found"); $response->setJsonContent(array('status' => 'ERROR', 'messages' => array('Unknown end-point'))); $response->send(); }); $app->handle();
if ($app->request->get('type') == 'csv') { $records = $app->getReturnedValue(); $response = new \PhalconRest\Responses\CSVResponse(); $response->useHeaderRow(true)->send($records); return; } else { throw new \PhalconRest\Exceptions\HTTPException('Could not return results in specified format', 403, array('dev' => 'Could not understand type specified by type paramter in query string.', 'internalCode' => 'NF1000', 'more' => 'Type may not be implemented. Choose either "csv" or "json"')); } } }); /** * The notFound service is the default handler function that runs when no route was matched. * We set a 404 here unless there's a suppress error codes. */ $app->notFound(function () use($app) { throw new \PhalconRest\Exceptions\HTTPException('Not Found.', 404, array('dev' => 'That route was not found on the server.', 'internalCode' => 'NF1000', 'more' => 'Check route for mispellings.')); }); /** * If the application throws an HTTPException, send it on to the client as json. * Elsewise, just log it. * TODO: Improve this. */ set_exception_handler(function ($exception) use($app) { //HTTPException's send method provides the correct response headers and body if (is_a($exception, 'PhalconRest\\Exceptions\\HTTPException')) { $exception->send(); } error_log($exception); error_log($exception->getTraceAsString()); }); $app->handle();
} return $response; }); // Send message to a selected user. $app->post('/chat/{sender}/{receiver}', function ($sender, $receiver) use($app) { $message = $app->request->getJsonRawBody(); $phql = "INSERT INTO Messages (sender_id, receiver_id, message_content)\n \t\tVALUES (:sender_id:, :receiver_id:, :message_content:)"; $status = $app->modelsManager->executeQuery($phql, array('sender_id' => $sender, 'receiver_id' => $receiver, 'message_content' => $message->message)); $response = new Phalcon\Http\Response(); if ($status->success() == true) { $phql = "SELECT * \n \t\t\tFROM Messages \n \t\t\tWHERE message_id = :message_id:"; $message = $app->modelsManager->executeQuery($phql, array('message_id' => $status->getModel()->message_id))->getFirst(); $response->setStatusCode(200, "Created"); $response->setJsonContent(array('status' => "OK", 'data' => $message)); } else { $response->setStatusCode(400, "Conflict"); $errors = array(); foreach ($status->getMessages() as $errorMessage) { $errors[] = $errorMessage->getMessage(); } $response->setJsonContent(array('status' => 'ERROR', 'messages' => $errors)); } return $response; }); // Handles the cases where a non-existing resource is called. $app->notFound(function () use($app) { $app->response->setStatusCode(404, "Not Found")->sendHeaders(); echo "You've just typed me, and this is crazy, but this page was not found, so it doesn't exist maybe!"; }); // Starts the application. $app->handle();
<?php $app = new Phalcon\Mvc\Micro(); $app->notFound(function () use($app) { $app->response->setStatusCode(404, 'Not Found')->sendHeaders(); echo 'Page not found.'; }); // begin route config $app->get('/api/test', function () { echo "HELLO WORLD"; }); $app->handle();
if ($app->request->getMethod() == 'OPTIONS') { $app->response->setStatusCode('200', 'OK'); $app->response->send(); return; } $res = $app->getReturnedValue(); $in = json_encode($res, FALSE); if ($in === null) { $response = $di->get('response'); $response->setContent($res); $response->send(); return; } if (!$app->request->get('type') || $app->request->get('type') == 'json') { $response = new \Modules\Core\Responses\JSONResponse(); $response->send($res); return; } else { throw new \Modules\Core\Exceptions\HTTPException('Could not return results in specified format', 403); } }); /** * Default handler when route is not found. */ $app->notFound(function () use($app) { throw new \Modules\Core\Exceptions\HTTPException('Not Found.', 404); }); /** * Run everything */ $app->handle();
}); /** * Default routes */ $app->get("/", function () use($app, $mongo) { $mdb = $mongo->selectDB(MDB_DB_NAME); $books = $mdb->selectCollection(MDB_COLLECTION); $json = array("version" => VERSION, "mongodb" => 'ok', "collection" => $books->getName(), "db" => "ok", "routes" => array()); foreach ($app->router->getRoutes() as $route) { $json["routes"][] = $route->getPattern(); } echo "<pre>"; echo json_encode($json, JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES); echo "</pre>"; }); $app->notFound(function () use($app) { $app->response->setStatusCode(404, "Not Found")->sendHeaders(); echo 'La url solicitada no existe!'; }); //Before middleware $app->before(function () use($app, $logger) { $logger->log("{$app->request->getScheme()} {$app->request->getHttpHost()} {$app->request->getMethod()} {$app->request->get("_url")}"); }); /** * Route handlers */ require "handlers/import.php"; require "handlers/books.php"; include "handlers/library_service.php"; //Handle request $app->handle();
//更新用户的基础信息 $app->post('/user', [new SnsController(), "update_myinfo"]); //获取用户详细信息 $app->get('/userinfo/{uid}', [new SnsController(), "userInfo"]); //更新用户信息 $app->post('/userinfo', [new SnsController(), "updateUserInfo"]); //获取附近在线用户 $app->get('/lbs/user/{gps}/{long}', function ($gps, $long) { $lbs = new LbsController(); $long = $long > 10000 ? 10000 : $long; $gps = explode(',', $gps); $lbs->findUserAction($gps, $long); }); //em 接口 $app->get('/im/adduser', [new EasemController(), "createUser"]); /** * SERVER IS OK */ $app->get('/', function () use($app) { sendMsg('Hello'); }); /** * Not find */ $app->notFound(function () use($app) { $app->response->setStatusCode(404, "Not Found")->sendHeaders(); }); $app->handle(); } catch (\Exception $e) { echo $e->getMessage(); }
/** * Tests the notFound * * @issue T169 * @author Nikos Dimopoulos <*****@*****.**> * @since 2012-11-06 */ public function testMicroNotFound_T169() { $handler = new RestHandler($this); $app = new \Phalcon\Mvc\Micro(); $app->get('/api/site', array($handler, 'find')); $app->post('/api/site/save', array($handler, 'save')); $flag = false; $app->notFound(function () use(&$flag) { $flag = true; }); $_SERVER['REQUEST_METHOD'] = 'GET'; $_GET['_url'] = '/fourohfour'; $app->handle(); $this->assertTrue($flag); }
$records = $app->getReturnedValue(); // this is default behavior $output->convertSnakeCase(false)->send($records); return; }); /** * The notFound service is the default handler function that runs when no route was matched. * We set a 404 here unless there's a suppress error codes. */ $app->notFound(function () use($app, $di) { $request = $di->get('request'); $query = $request->getQuery(); $url = '?'; $count = 0; foreach ($query as $key => $value) { if ($count > 0) { $url .= "&"; } $url .= "{$key}={$value}"; $count++; } throw new \PhalconRest\Util\HTTPException('Not Found.', 404, array('dev' => "That route was not found on the server: " . $url, 'code' => '4', 'more' => 'Check route for mispellings.')); }); /** * If the application throws an HTTPException, send it on to the client as json. * Elsewise, just log it. * TODO: Improve this. * TODO: Kept here due to dependency on $app */ set_exception_handler(function ($exception) use($app, $config) { // $config = $di->get('config'); // HTTPException's send method provides the correct response headers and body
// not efficient } echo implode('<br /><br />', $output); }); // view the error log $app->get('/errors', function () use($app) { $redis = $app->di->get('redis'); $output = []; foreach ($redis->zrange('error-log', 0, time()) as $entry) { $entry = json_decode($entry, true); $msg = '<strong>' . date('Y-m-d H:i:s', $entry['key'] / 1000) . "</strong> - MSG: " . json_encode($entry['msg']) . " - DATA: " . json_encode($entry['data']); array_unshift($output, $msg); // not efficient } echo implode('<br /><br />', $output); }); // no found route $app->notFound(function () use($app) { $response = new Phalcon\Http\Response(); $response->setStatusCode(404, "Not Found"); $response->send(); die; }); try { $app->handle(); } catch (\Exception $e) { // log internal error message $response = new Phalcon\Http\Response(); $response->setStatusCode(500, "Internal Error"); $response->send(); }
/** * Registering an autoloader */ $loader = new \Phalcon\Loader(); $loader->registerDirs(array($config->application->modelsDir))->register(); /** * Starting the application */ $app = new \Phalcon\Mvc\Micro(); /** * Add your routes here */ $app->get('/', function () { require __DIR__ . "/../views/index.phtml"; }); /** * Not found handler */ $app->notFound(function () use($app) { $app->response->setStatusCode(404, "Not Found")->sendHeaders(); require __DIR__ . "/../views/404.phtml"; }); /** * Handle the request */ $app->handle(); } catch (Phalcon\Exception $e) { echo $e->getMessage(); } catch (PDOException $e) { echo $e->getMessage(); }
/** * Handles the request. */ public function main() { /** * Our application is a Micro application, so we must explicitly define all the routes. * For APIs, this is ideal. This is as opposed to the more robust MVC Application * @var $app */ $app = new \Phalcon\Mvc\Micro(); $app->setDI($this->di); /** * This will require changes to fit your application structure. * It supports Auth, Session auth, and Exempted routes. * It also allows all Options requests, as those tend to not come with * cookies or basic auth credentials and Preflight is not implemented the * same in every browser. */ $app->before(function () use($app) { // Oauth, for programmatic responses if ($app->request->getHeader('X_COMPARE_REST_API_KEY') && $app->request->get('language') && $app->request->get('countryCode')) { $session = new SessionsController(); $result = $session->resource($app->request->getHeader('X_COMPARE_REST_API_KEY')); if ($result) { return true; } else { throw new HTTPException('Invalid access token.', 401, ['dev' => 'Please provide credentials by passing your access token.', 'internalCode' => 'Unauth:1']); } } // If we made it this far, we have no valid auth method, throw a 401. throw new HTTPException('Must provide credentials.', 401, ['dev' => 'Please provide credentials by passing your access token, language and country code.', 'internalCode' => 'Unauth:1']); return false; }); /** * Mount all of the collections, which makes the routes active. */ foreach ($this->di->getShared('collections') as $collection) { $app->mount($collection); } /** * The base route return the list of defined routes for the application. * This is not strictly REST compliant, but it helps to base API documentation off of. * By calling this, you can quickly see a list of all routes and their methods. */ $app->get('/', function () use($app) { $routes = $app->getRouter()->getRoutes(); $routeDefinitions = array('GET' => array(), 'POST' => array(), 'PUT' => array(), 'PATCH' => array(), 'DELETE' => array(), 'HEAD' => array(), 'OPTIONS' => array()); foreach ($routes as $route) { $method = $route->getHttpMethods(); $routeDefinitions[$method][] = $route->getPattern(); } return $routeDefinitions; }); /** * After a route is run, usually when its Controller returns a final value, * the application runs the following function which actually sends the response to the client. * * The default behavior is to send the Controller's returned value to the client as JSON. * However, by parsing the request querystring's 'type' paramter, it is easy to install * different response type handlers. Below is an alternate csv handler. */ $app->after(function () use($app) { // OPTIONS have no body, send the headers, exit if ($app->request->getMethod() == 'OPTIONS') { $app->response->setStatusCode('200', 'OK'); $app->response->send(); return; } // Respond by default as JSON if (!$app->request->get('type') || 'json' == $app->request->get('type') || 'option' == $app->request->get('type')) { // Results returned from the route's controller. All Controllers should return an array $records = $app->getReturnedValue(); $response = new JSONResponse(); $response->useEnvelope(true)->convertSnakeCase(true)->send($records); return; } else { if ('xml' == $app->request->get('type')) { $records = $app->getReturnedValue(); $response = new XMLResponse(); $response->send($records); return; } else { if ('csv' == $app->request->get('type')) { $records = $app->getReturnedValue(); $response = new CSVResponse(); $response->useHeaderRow(true)->send($records); return; } else { throw new HTTPException('Could not return results in specified format', 403, array('dev' => 'Could not understand type specified by type paramter in query string.', 'internalCode' => 'NF1000', 'more' => 'Type may not be implemented. Choose either "json", "xml" or "csv"')); } } } }); /** * The notFound service is the default handler function that runs when no route was matched. * We set a 404 here unless there's a suppress error codes. */ $app->notFound(function () use($app) { throw new HTTPException('Not Found.', 404, array('dev' => 'That route was not found on the server.', 'internalCode' => 'NF1000', 'more' => 'Check route for mispellings.')); }); /** * If the application throws an HTTPException, send it on to the client as json. * Elsewise, just log it. */ set_exception_handler(function ($exception) use($app) { //HTTPException's send method provides the correct response headers and body if (is_a($exception, 'App\\Common\\Lib\\Application\\Exceptions\\HTTPException')) { $exception->send(); } error_log($exception); error_log($exception->getTraceAsString()); }); $app->handle(); }
$app->after(function () use($app) { $method = $app->request->getMethod(); $output = new \PhalconRest\API\Output(); switch ($method) { case 'OPTIONS': $app->response->setStatusCode('200', 'OK'); $app->response->send(); return; break; case 'DELETE': $app->response->setStatusCode('204', 'No Content'); $app->response->send(); return; break; case 'POST': $output->setStatusCode('201', 'Created'); break; } // Results returned from the route's controller. All Controllers should return an array $records = $app->getReturnedValue(); // this is default behavior $output->convertSnakeCase(false)->send($records); return; }); /** * The notFound service is the default handler function that runs when no route was matched. * We set a 404 here unless there's a suppress error codes. */ $app->notFound(function () use($app) { throw new \PhalconRest\Util\HTTPException('Not Found.', 404, array('dev' => 'That route was not found on the server.', 'code' => '4', 'more' => 'Check route for misspellings.')); });
<?php $app = new Phalcon\Mvc\Micro(); $app->get('/', function () { echo "<h1>Welcome!</h1>"; }); $app->get('/say/hello/{name}', function ($name) use($app) { echo "<h1>Hello! {$name}</h1>"; echo "Your IP Address is ", $app->request->getClientAddress(); }); $app->post('/store/something', function () use($app) { $name = $app->request->getPost('name'); echo "<h1>Hello! {$name}</h1>"; }); $app->notFound(function () use($app) { $app->response->setStatusCode(404, "Not Found")->sendHeaders(); echo 'This is crazy, but this page was not found!'; }); $app->handle();