daurnimator / lua-http

HTTP Library for Lua. Supports HTTP(S) 1.0, 1.1 and 2.0; client and server.
https://daurnimator.github.io/lua-http/
MIT License
778 stars 80 forks source link

allow new_from_uri to accept headers? #221

Closed bjacobson26 closed 2 months ago

bjacobson26 commented 3 months ago

Hi there,

I need to pass in authorization headers when connecting to a websocket server. Seems like this currently is not supported.

I patched it locally to work:

local function new_from_uri(uri, protocols, headers)
  local request = http_request.new_from_uri(uri)
  local self = new("client")
  self.request = request
  self.request.version = 1.1
  self.request.headers:append("upgrade", "websocket")
  self.request.headers:append("connection", "upgrade")
  self.key = new_key()
  self.request.headers:append("sec-websocket-key", self.key, true)
  self.request.headers:append("sec-websocket-version", "13")
  if headers then
    for k, v in pairs(headers) do
      self.request.headers:append(k, v)
    end
  end
  ....
local headers = {
  ["Authorization"] = jwt,
  ["Something-Else"] = foobar
}

websocket.new_from_uri(ws_url, nil, headers)

Wondering if there is any reason I shouldn't do this and/or if you'd like me to open a PR for this.

Thanks!

daurnimator commented 2 months ago

I need to pass in authorization headers when connecting to a websocket server. Seems like this currently is not supported.

Sure it is:

local ws = http_websocket.new_from_uri(myuri)
ws.request.headers:append("Authorization", mything)
assert(ws:connect())