开源软件名称(OpenSource Name):ledgetech/lua-resty-http开源软件地址(OpenSource Url):https://github.com/ledgetech/lua-resty-http开源编程语言(OpenSource Language):Lua 99.5%开源软件介绍(OpenSource Introduction):lua-resty-httpLua HTTP client cosocket driver for OpenResty / ngx_lua. StatusProduction ready. Features
API
DeprecatedThese methods may be removed in future versions. UsageThere are two basic modes of operation:
Single-shot requestlocal httpc = require("resty.http").new()
-- Single-shot requests use the `request_uri` interface.
local res, err = httpc:request_uri("http://example.com/helloworld", {
method = "POST",
body = "a=1&b=2",
headers = {
["Content-Type"] = "application/x-www-form-urlencoded",
},
})
if not res then
ngx.log(ngx.ERR, "request failed: ", err)
return
end
-- At this point, the entire request / response is complete and the connection
-- will be closed or back on the connection pool.
-- The `res` table contains the expeected `status`, `headers` and `body` fields.
local status = res.status
local length = res.headers["Content-Length"]
local body = res.body Streamed requestlocal httpc = require("resty.http").new()
-- First establish a connection
local ok, err, ssl_session = httpc:connect({
scheme = "https",
host = "127.0.0.1",
port = 8080,
})
if not ok then
ngx.log(ngx.ERR, "connection failed: ", err)
return
end
-- Then send using `request`, supplying a path and `Host` header instead of a
-- full URI.
local res, err = httpc:request({
path = "/helloworld",
headers = {
["Host"] = "example.com",
},
})
if not res then
ngx.log(ngx.ERR, "request failed: ", err)
return
end
-- At this point, the status and headers will be available to use in the `res`
-- table, but the body and any trailers will still be on the wire.
-- We can use the `body_reader` iterator, to stream the body according to our
-- desired buffer size.
local reader = res.body_reader
local buffer_size = 8192
repeat
local buffer, err = reader(buffer_size)
if err then
ngx.log(ngx.ERR, err)
break
end
if buffer then
-- process
end
until not buffer
local ok, err = httpc:set_keepalive()
if not ok then
ngx.say("failed to set keepalive: ", err)
return
end
-- At this point, the connection will either be safely back in the pool, or closed. Connectionnew
Creates the HTTP connection object. In case of failures, returns connect
Attempts to connect to the web server while incorporating the following activities:
In doing so it will create a distinct connection pool name that is safe to use with SSL and / or proxy based connections, and as such this syntax is strongly recommended over the original (now deprecated) TCP only connection syntax. The options table has the following fields:
set_timeout
Sets the socket timeout (in ms) for subsequent operations. See set_timeouts below for a more declarative approach. set_timeouts
Sets the connect timeout threshold, send timeout threshold, and read timeout threshold, respectively, in milliseconds, for subsequent socket operations (connect, send, receive, and iterators returned from receiveuntil). set_keepalive
Either places the current connection into the pool for future reuse, or closes the connection. Calling this instead of close is "safe" in that it will conditionally close depending on the type of request. Specifically, a In case of success, returns See OpenResty docs for parameter documentation. set_proxy_options
Configure an HTTP proxy to be used with this client instance. The
Note that this method has no effect when using the deprecated TCP only connect connection syntax. get_reused_times
See OpenResty docs. close
See OpenResty docs. Requestingrequest
Sends an HTTP request over an already established connection. Returns a The
When the request is successful,
request_uri
The single-shot interface (see usage). Since this method performs an entire end-to-end request, options specified in the There are 3 additional parameters for controlling keepalives:
If the request is successful,
request_pipeline
This method works as per the request method above, but local responses = httpc:request_pipeline({
{ path = "/b" },
{ path = "/c" },
{ path = "/d" },
})
for _, r in ipairs(responses) do
if not r.status then
ngx.log(ngx.ERR, "socket read error")
break
end
ngx.say(r.status)
ngx.say(r:read_body())
end Due to the nature of pipelining, no responses are actually read until you attempt to use the response fields (status / headers etc). And since the responses are read off in order, you must read the entire body (and any trailers if you have them), before attempting to read the next response. Note this doesn't preclude the use of the streaming response body reader. Responses can still be streamed, so long as the entire body is streamed before attempting to access the next response. Be sure to test at least one field (such as status) before trying to use the others, in case a socket read error has occurred. Responseres.body_readerThe local reader = res.body_reader
local buffer_size = 8192
repeat
local buffer, err = reader(buffer_size)
if err then
ngx.log(ngx.ERR, err)
break
end
if buffer then
-- process
end
until not buffer If the reader is called with no arguments, the behaviour depends on the type of connection. If the response is encoded as chunked, then the iterator will return the chunks as they arrive. If not, it will simply return the entire body. Note that the size provided is actually a maximum size. So in the chunked transfer case, you may get buffers smaller than the size you ask, as a remainder of the actual encoded chunks. res:read_body
Reads the entire body into a local string. res:read_trailers
This merges any trailers underneath the Utilityparse_uri
This is a convenience function allowing one to more easily use the generic interface, when the input data is a URI. As of version get_client_body_reader
Returns an iterator function which can be used to read the downstream client request body in a streaming fashion. You may also specify an optional default chunksize (default is Example: local req_reader = httpc:get_client_body_reader()
local buffer_size = 8192
repeat
local buffer, err = req_reader(buffer_size)
if err then
ngx.log(ngx.ERR, err)
break
end
if buffer then
-- process
end
until not buffer This iterator can also be used as the value for the body field in request params, allowing one to stream the request body into a proxied upstream request. local client_body_reader, err = httpc:get_client_body_reader()
local res, err = httpc:request({
path = "/helloworld",
body = client_body_reader,
}) DeprecatedThese features remain for backwards compatability, but may be removed in future releases. TCP only connectThe following versions of the
NOTE: the default pool name will only incorporate IP and port information so is unsafe to use in case of SSL and/or Proxy connections. Specify your own pool or, better still, do not use these signatures. connect_proxy
Calling this method manually is no longer necessary since it is incorporated within connect. It is retained for now for compatibility with users of the older TCP only connect syntax. Attempts to connect to the web server through the given proxy server. The method accepts the following arguments:
If an error occurs during the connection attempt, this method returns There's a few key points to keep in mind when using this api:
ssl_handshake
Calling this method manually is no longer necessary since it is incorporated within connect. It is retained for now for compatibility with users of the older TCP only connect syntax. See OpenResty docs. proxy_request / proxy_responseThese two convenience methods were intended simply to demonstrate a common use case of implementing reverse proxying, and the author regrets their inclusion in the module. Users are encouraged to roll their own rather than depend on these functions, which may be removed in a subsequent release. proxy_request
Performs a request using the current client request arguments, effectively proxying to the connected upstream. The request body will be read in a streaming fashion, according to proxy_response
Sets the current response based on the given AuthorJames Hurst james@pintsized.co.uk, with contributions from @hamishforbes, @Tieske, @bungle et al. LicenceThis module is licensed under the 2-clause BSD license. Copyright (c) James Hurst james@pintsized.co.uk All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论