hres and hres_json for responses

This commit is contained in:
Bofh 2021-11-25 16:43:35 +01:00
parent 3ad1d22f46
commit 96d6b5f083
3 changed files with 23 additions and 16 deletions

View File

@ -3,12 +3,8 @@
$instance = resolve_instance($_GET['instance'] ?? ''); $instance = resolve_instance($_GET['instance'] ?? '');
if ($instance === false) { if ($instance === false) {
http_response_code(400); hres_json(400, ERR, lr('error.instance_not_exists',
die(json_encode([ 'Instance does not exist or is incorrect.'));
'status' => 'error',
'message' => lr('error.instance_not_exists',
'Instance does not exist or is incorrect.')
]));
} }
$app_name = conf('app_name', 'RealFan'); $app_name = conf('app_name', 'RealFan');
@ -33,12 +29,8 @@ curl_close($ch);
# result must be JSON # result must be JSON
$result = @json_decode($result); $result = @json_decode($result);
if ($result === null) { if ($result === null) {
http_response_code(500); hres_json(500, ERR, lr('error.instance_failed_or_not_mastodon',
die(json_encode([ 'Instance failed to create an authorization App. Is it an instance?'));
'status' => 'error',
'message' => lr('error.instance_failed_or_not_mastodon',
'Instance failed to create an authorization App. Is it an instance?')
]));
} }
# create the URL for OAUTH # create the URL for OAUTH
@ -48,7 +40,4 @@ $query_string = http_build_query([
'response_type' => 'code', 'response_type' => 'code',
'scope' => $scopes 'scope' => $scopes
]); ]);
echo json_encode([ hres_json(200, OK, $instance.'/oauth/authorize?'.$query_string);
'status' => 'ok',
'message' => $instance.'/oauth/autorize?'.$query_string
]);

View File

@ -1,5 +1,20 @@
<?php <?php
# HTTP result => JSON
function hres_json($code, $status, $message) {
header('Content-Type: application/json');
return hres(json_encode([
'status' => $status,
'message' => $message
]), $code);
}
# HTTP result
function hres($message, $code=200) {
http_response_code($code);
die($message);
}
# Support instance aliases! # Support instance aliases!
function resolve_instance($txt) { function resolve_instance($txt) {
$txt = preg_replace('/^https?:\/\//', '', strtolower(trim($txt))); $txt = preg_replace('/^https?:\/\//', '', strtolower(trim($txt)));

View File

@ -1,5 +1,8 @@
<?php <?php
define('OK', 'ok');
define('ERR', 'err');
$env = 'prod'; $env = 'prod';
if (getenv('ENV') !== false && in_array(getenv('ENV'), ['prod', 'dev'])) if (getenv('ENV') !== false && in_array(getenv('ENV'), ['prod', 'dev']))
$env = getenv('ENV'); $env = getenv('ENV');