daraja restful
2.5
ส่วนขยายที่พักผ่อนสำหรับเฟรมเวิร์ก Daraja HTTP
นี่คือตัวอย่างสั้น ๆ มันลงทะเบียนตัวจัดการคำขอที่ Path 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 จะถูกส่งไปยังตัวจัดการคำขอ parametrized นี้:
&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);