ngx.req和get/post引數獲取
ngx.req.raw_header 和ngx.req.get_headers示例
(1)ngx.req.raw_header
函式原型: headers = ngx.req.get_headers(max_headers?, raw?)
返回值型別為table,其大概的內容如下:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding:gzip, deflate, br
Accept-Language:zh-CN,zh;q=0.8,en;q=0.6
Cache-Control:max-age=0
Connection:keep-alive
Host:localhost:8080
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
(2)ngx.req.get_headers
函式原型:str = ngx.req.raw_header(no_request_line?)
返回值型別為是string,其大概的內容如下:
GET /echo/cyrus HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
Upgrade-Insecure-Requests: 1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.8,en;q=0.6
以上內容因使用的web client不同,輸出的內容也有較大的差異,但是一些基本的資訊和格式大致是相同的。
在使用中,一般都可以通過特定的函式獲取到指定的內容,比如host/uri/method/http_version等。
ngx.req.get_uri_args 和 ngx.req.get_post_args示例
(1)ngx.req.get_uri_args
函式原型:args = ngx.req.get_uri_args(max_args?)
返回型別為table,可以使用以下方式遍歷:
for key, val in pairs(args) do
...
end
hello, cyrus
age:2
name:true
無法獲取到path Variable的變數和值。對於path variable的獲取使用以下方式:
ngx.say("hello, ",ngx.var[1])
注意這裡的下標是從1開始。
(2)ngx.req.get_post_args
函式原型:args, err = ngx.req.get_post_args(max_args?)
返回值型別為table,遍歷方式同(1)。其請求的方式為:
curl --data 'foo=bar&bar=baz&bar=blah' localhost/test
結果為:
foo: bar
bar: baz, blah
注意這裡可以多次定義同一個key(比如bar),解析時作為一個可以有多個值,且使用逗號進行分割。Web使用json格式傳送post請求更為常見,這裡就可以使用ngx.req.get_body_data
(3)ngx.req.get_body_data
函式原型:data = ngx.req.get_body_data()
返回值型別為string,對於接收到的字串可以進行json解碼,從而實現json引數的傳遞。