This forum uses cookies
This forum makes use of cookies to store your login information if you are registered, and your last visit if you are not. Cookies are small text documents stored on your computer; the cookies set by this forum can only be used on this website and pose no security risk. Cookies on this forum also track the specific topics you have read and when you last read them. Please confirm whether you accept or reject these cookies being set.

https function
#1
i make dynamic function to call https command and to add headers like the below,

Code:
function Https_message(method, url, payload, add_headers) --method is "POST", "GET" "PUT" etc

htps = require("ssl.https")
msg_response = {}
hders = {} 
 
  if payload or add_headers then
   
    if payload then
    hders = { ["Accept"] = "*/*",
          ["Content-Type"] = "application/json",
          ["Content-Length"] = #payload,
          ['Host']  = ip..':'..port}
    else
      hders = { ["Accept"] = "*/*", ["Content-Type"] = "application/json", ['Host']  = ip..':'..port}
    end
   
    if add_headers then
  for k, v in pairs(add_headers) do
    hders[k] = v
   end
  end
   
  end
 
local res, err, res_headers, status = htps.request
  {
    url = url,
    method = method,
    protocol = 'tlsv12',
    headers = hders,
    verify = "none",
   
  source = ltn12.source.string(payload),        
  sink = ltn12.sink.table(msg_response)
  }
  return msg_response, err, res_headers
end

My problem is, if i call get command like
Code:
local msg_response, err, Https_message('GET', 192.168.1.1:443/etc/etc, nil, nil)
log(msg_response, err)
with var payload set to nil, the msg_response var returns nil,
i think because, source = ltn12.source.string(payload) would be nil


2 Questions
1- Is the ltn12.source tied together with the ltn12.sink if the source var is present?
2- How can i ignore the ltn12.source if function payload var is set to nil?
Reply
#2
Do not set the source if payload is not provided:
Code:
local source

if payload then
  source = ltn12.source.string(payload)
end

...

local res, err, res_headers, status = htps.request({
  ...
  source = source, -- source will be nil if payload is not provided
  ...
})

There's another issue with your code when payload or add_headers are set: ip/port variables are not set, so the function call will produce an error. You can use socket.url to parse the url into parts: http://w3.impa.br/~diego/software/luasoc...html#parse
Reply


Forum Jump: