daraja restful
2.5
Daraja HTTP框架的靜止擴展
這是一個簡短的示例,它在路徑Hello上註冊一個請求處理程序,該請求處理程序處理HTTP獲取請求,但前提是HTTP請求還指定客戶端接受內容類型文本/HTML的響應。 (如果HTTP客戶端試圖提交發布請求,或者客戶端指定其他內容類型,則將返回HTTP錯誤響應)。
&Path('hello');
&Produces('text/html');
GET
(procedure(Request: TdjRequest; Response: TdjResponse)
begin
Response.ContentText := '<html>Hello world!</html>';
end);
該框架支持路徑參數,因此http://mydomain.local/myapp/orders/123將被路由到此參數化請求處理程序:
&Path('orders/{orderId}')
&Produces('text/html');
GET
(procedure(Request: TdjRequest; Response: TdjResponse)
begin
Response.ContentText :=
Format('<html>Thank you for your order %s</html>',
[Request.Params.Values['orderId']]);
end);
如果資源具有多個表示形式(HTML,XML或JSON),則可以使用相同的路徑值來處理,但不同的MIME類型會產生屬性:
// respond to HTML browsers
&Path('myresource');
&Produces('text/html');
GET(procedure(Request: TdjRequest; Response: TdjResponse)
begin
Response.ContentText :=
'<html>Hello world!</html>';
end);
// respond to XML client
&Path('myresource');
&Produces('application/xml');
GET(procedure(Request: TdjRequest; Response: TdjResponse)
begin
Response.ContentText := '<xml>Hello world!</xml>';
Response.CharSet := 'utf-8';
end);
// respond to JSON client
&Path('myresource');
&Produces('application/json');
GET(procedure(Request: TdjRequest; Response: TdjResponse)
begin
Response.ContentText := '{"msg":"Hello world!"}';
Response.CharSet := 'utf-8';
end);