-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexamples.pl
More file actions
executable file
·316 lines (257 loc) · 9.34 KB
/
examples.pl
File metadata and controls
executable file
·316 lines (257 loc) · 9.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#!/usr/bin/env perl
# TinyServe - Advanced Usage Examples
# This file demonstrates how to extend TinyServe with custom routes and middleware
use strict;
use warnings;
# Example 1: Custom API Routes
# Add these to the register_default_routes() function in tinyserve.pl
sub example_custom_routes {
# Simple GET route with query parameters
register_route('GET', '/api/greet', sub {
my ($req, $res) = @_;
my $name = $req->{params}{name} || 'Guest';
$res->{status} = 200;
$res->{headers}{'Content-Type'} = 'application/json';
$res->{body} = encode_json({
greeting => "Hello, $name!",
timestamp => time()
});
});
# POST route with JSON body
register_route('POST', '/api/users', sub {
my ($req, $res) = @_;
my $user = $req->{json};
# Validate input
unless ($user && $user->{name} && $user->{email}) {
$res->{status} = 400;
$res->{headers}{'Content-Type'} = 'application/json';
$res->{body} = encode_json({
error => 'Missing required fields: name, email'
});
return;
}
# Simulate saving user
my $new_user = {
id => int(rand(10000)),
name => $user->{name},
email => $user->{email},
created_at => time()
};
$res->{status} = 201;
$res->{headers}{'Content-Type'} = 'application/json';
$res->{body} = encode_json({
success => 1,
user => $new_user
});
});
# PUT route for updates
register_route('PUT', '/api/users/123', sub {
my ($req, $res) = @_;
my $updates = $req->{json};
$res->{status} = 200;
$res->{headers}{'Content-Type'} = 'application/json';
$res->{body} = encode_json({
success => 1,
message => 'User updated',
updates => $updates
});
});
# DELETE route
register_route('DELETE', '/api/users/123', sub {
my ($req, $res) = @_;
$res->{status} = 204;
$res->{headers}{'Content-Type'} = 'application/json';
$res->{body} = '';
});
# File upload simulation (form data)
register_route('POST', '/api/upload', sub {
my ($req, $res) = @_;
$res->{status} = 200;
$res->{headers}{'Content-Type'} = 'application/json';
$res->{body} = encode_json({
success => 1,
message => 'File uploaded',
size => length($req->{body}),
content_type => $req->{headers}{'content-type'}
});
});
}
# Example 2: Middleware Examples
# Add these using add_middleware() before starting the server
sub example_cors_middleware {
add_middleware(sub {
my ($req, $res) = @_;
# Add CORS headers
$res->{headers}{'Access-Control-Allow-Origin'} = '*';
$res->{headers}{'Access-Control-Allow-Methods'} = 'GET, POST, PUT, DELETE, OPTIONS';
$res->{headers}{'Access-Control-Allow-Headers'} = 'Content-Type, Authorization';
# Handle preflight requests
if ($req->{method} eq 'OPTIONS') {
$res->{status} = 204;
$res->{body} = '';
return 0; # Stop processing
}
return 1; # Continue processing
});
}
sub example_auth_middleware {
add_middleware(sub {
my ($req, $res) = @_;
# Only protect /api/admin routes
if ($req->{path} =~ m{^/api/admin}) {
my $auth = $req->{headers}{authorization} || '';
# Simple token validation
unless ($auth eq 'Bearer secret-token-12345') {
$res->{status} = 401;
$res->{headers}{'Content-Type'} = 'application/json';
$res->{body} = encode_json({
error => 'Unauthorized',
message => 'Valid authorization token required'
});
return 0; # Stop processing
}
}
return 1; # Continue processing
});
}
sub example_rate_limit_middleware {
my %request_counts = ();
my $limit = 100; # requests per minute
my $window = 60; # seconds
add_middleware(sub {
my ($req, $res) = @_;
# Get client IP (simplified)
my $client_ip = $req->{headers}{'x-forwarded-for'} || 'unknown';
my $now = time();
# Clean old entries
foreach my $ip (keys %request_counts) {
if ($now - $request_counts{$ip}{time} > $window) {
delete $request_counts{$ip};
}
}
# Check rate limit
if (exists $request_counts{$client_ip}) {
$request_counts{$client_ip}{count}++;
if ($request_counts{$client_ip}{count} > $limit) {
$res->{status} = 429;
$res->{headers}{'Content-Type'} = 'application/json';
$res->{body} = encode_json({
error => 'Too Many Requests',
message => "Rate limit exceeded: $limit requests per minute"
});
return 0; # Stop processing
}
} else {
$request_counts{$client_ip} = {
count => 1,
time => $now
};
}
return 1; # Continue processing
});
}
sub example_logging_middleware {
add_middleware(sub {
my ($req, $res) = @_;
# Add custom request ID
my $request_id = sprintf("%08x", int(rand(0xFFFFFFFF)));
$res->{headers}{'X-Request-ID'} = $request_id;
# Log request details
print "[REQUEST-$request_id] $req->{method} $req->{path}\n";
return 1; # Continue processing
});
}
sub example_cache_control_middleware {
add_middleware(sub {
my ($req, $res) = @_;
# Add cache headers for static files
if ($req->{path} =~ /\.(css|js|png|jpg|jpeg|gif|svg|woff|woff2)$/) {
$res->{headers}{'Cache-Control'} = 'public, max-age=3600';
} else {
$res->{headers}{'Cache-Control'} = 'no-cache, no-store, must-revalidate';
}
return 1; # Continue processing
});
}
# Example 3: RESTful API with in-memory database
sub example_rest_api {
my @todos = (
{ id => 1, title => 'Learn Perl', completed => 1 },
{ id => 2, title => 'Build TinyServe', completed => 1 },
{ id => 3, title => 'Deploy app', completed => 0 },
);
my $next_id = 4;
# GET all todos
register_route('GET', '/api/todos', sub {
my ($req, $res) = @_;
$res->{status} = 200;
$res->{headers}{'Content-Type'} = 'application/json';
$res->{body} = encode_json(\@todos);
});
# GET single todo
register_route('GET', '/api/todos/1', sub {
my ($req, $res) = @_;
my $id = 1; # In real app, extract from path
my ($todo) = grep { $_->{id} == $id } @todos;
if ($todo) {
$res->{status} = 200;
$res->{headers}{'Content-Type'} = 'application/json';
$res->{body} = encode_json($todo);
} else {
$res->{status} = 404;
$res->{headers}{'Content-Type'} = 'application/json';
$res->{body} = encode_json({ error => 'Todo not found' });
}
});
# POST new todo
register_route('POST', '/api/todos', sub {
my ($req, $res) = @_;
my $data = $req->{json};
unless ($data && $data->{title}) {
$res->{status} = 400;
$res->{headers}{'Content-Type'} = 'application/json';
$res->{body} = encode_json({ error => 'Title is required' });
return;
}
my $new_todo = {
id => $next_id++,
title => $data->{title},
completed => $data->{completed} || 0
};
push @todos, $new_todo;
$res->{status} = 201;
$res->{headers}{'Content-Type'} = 'application/json';
$res->{body} = encode_json($new_todo);
});
}
# Example 4: Testing with curl commands
print <<"EXAMPLES";
TinyServe - Advanced Usage Examples
====================================
1. Test GET with query parameters:
curl "http://localhost:8080/api/greet?name=John"
2. Test POST with JSON:
curl -X POST http://localhost:8080/api/users \\
-H "Content-Type: application/json" \\
-d '{"name":"John Doe","email":"john\@example.com"}'
3. Test PUT request:
curl -X PUT http://localhost:8080/api/users/123 \\
-H "Content-Type: application/json" \\
-d '{"name":"Jane Doe"}'
4. Test DELETE request:
curl -X DELETE http://localhost:8080/api/users/123
5. Test with authentication:
curl http://localhost:8080/api/admin/users \\
-H "Authorization: Bearer secret-token-12345"
6. Test form data:
curl -X POST http://localhost:8080/api/upload \\
-F "file=@image.png"
7. Test CORS preflight:
curl -X OPTIONS http://localhost:8080/api/status \\
-H "Access-Control-Request-Method: POST"
8. Test todos API:
curl http://localhost:8080/api/todos
curl -X POST http://localhost:8080/api/todos \\
-H "Content-Type: application/json" \\
-d '{"title":"New task","completed":false}'
EXAMPLES