forked from openresty/openresty.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRoutingMySQLQueriesBasedOnURIArgs
68 lines (54 loc) · 2.01 KB
/
RoutingMySQLQueriesBasedOnURIArgs
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
This sample demonstrates how to route incoming requests to different MySQL queries based on different combinations of URI query arguments, preserving streaming output capabilities provided by DrizzleNginxModule and RdsJsonNginxModule.
This demo uses the modules DrizzleNginxModule, LuaNginxModule, RdsJsonNginxModule, and SetMiscNginxModule bundled by OpenResty.
Here's the complete code listing for our `nginx.conf`:
```
worker_processes 2;
error_log logs/error.log warn;
events {
worker_connections 1024;
}
http {
upstream backend {
drizzle_server 127.0.0.1:3306 protocol=mysql
dbname=ngx_test user=ngx_test password=ngx_test;
drizzle_keepalive max=10 overflow=ignore mode=single;
}
server {
listen 8080;
location @cats-by-name {
set_unescape_uri $name $arg_name;
set_quote_sql_str $name;
drizzle_query 'select * from cats where name=$name';
drizzle_pass backend;
rds_json on;
}
location @cats-by-id {
set_quote_sql_str $id $arg_id;
drizzle_query 'select * from cats where id=$id';
drizzle_pass backend;
rds_json on;
}
location = /cats {
access_by_lua '
if ngx.var.arg_name then
return ngx.exec("@cats-by-name")
end
if ngx.var.arg_id then
return ngx.exec("@cats-by-id")
end
';
rds_json_ret 400 "expecting \"name\" or \"id\" query arguments";
}
}
}
```
And then we start our Nginx server with this configure file and test with our `/cats` service like this:
```
$ curl 'localhost:8080/cats'
{"errcode":400,"errstr":"expecting \"name\" or \"id\" query arguments"}
$ curl 'localhost:8080/cats?name=bob'
[{"id":3,"name":"bob"}]
$ curl 'localhost:8080/cats?id=2'
[{"id":2,"name":null}]
```
The actual output rows may vary depending on the actual contents in your `cats` table anyway.