lib/waxx/res.rb in waxx-0.1.4 vs lib/waxx/res.rb in waxx-0.2.0

- old
+ new

@@ -17,11 +17,11 @@ ## # The Response Struct gets instanciated with each request (x.res) # # ``` # x.res[name] = value # Set a response header - # x.res.as(extention) # Set the Content-Type header based on extension + # x.res.as(extention) # Set the content-type header based on extension # x.res.redirect '/path' # Redirect the client with 302 / Location header # x.res.location '/path' # Redirect the client with 302 / Location header # x.res.cookie( # Set a cookie # name: "", # value: nil, @@ -43,11 +43,13 @@ :error, :cookies, :no_cookies ) do - # Send output to the client (may be buffered) + attr :headers_sent + + # Send output to the client buffered until flush() or complete() def << str out << str end def [](n,v) @@ -57,11 +59,11 @@ def []=(n,v) headers[n] = v end def as(ext) - headers['Content-Type'] = Waxx::Http.ctype(ext) + headers['content-type'] = Waxx::Http.ctype(ext) end def location(uri) self.status = 302 headers['Location'] = uri @@ -77,17 +79,33 @@ "Set-Cookie: #{c}" } unless no_cookies), "\r\n" ].flatten.join("\r\n") end + + def flush(content=nil) + unless @headers_sent + server.print head + @headers_sent = true + end + if content.nil? + server.print out.join + out.clear + else + server.print content + end + end # Output the headers and the body def complete re = out.join - headers["Content-Length"] = re.bytesize + headers["content-length"] = re.bytesize if headers['content-length'].nil? begin - server.print head + unless @headers_sent + server.print head + @headers_sent = true + end server.print re # Connection reset by peer rescue Errno::ECONNRESET => e Waxx.debug(e.class) Waxx.debug(e) @@ -98,12 +116,18 @@ Waxx.debug(e) Waxx.debug(e.backtrace.join("\n")) end end - def cookie(name:"", value:nil, domain:nil, expires:nil, path:"/", secure:true, http_only: false, same_site: "Lax") - expires = expires.nil? ? "" : "expires=#{Time === expires ? expires.rfc2822 : expires}; " - cookies << "#{name}=#{Waxx::Http.escape(value.to_s)}; #{expires}#{";domain=#{domain}" if domain}; path=#{path}#{"; secure" if secure}#{"; HttpOnly" if http_only}; SameSite=#{same_site}" + def cookie(name: "", value: nil, domain: nil, expires: nil, path: "/", secure: true, http_only: false, same_site: "Lax") + c = ["#{name}=#{Waxx::Http.escape(value.to_s)}"] + c << "Path=#{path}" + c << "SameSite=#{same_site}" + c << "Expires=#{Time === expires ? expires.rfc2822 : expires}" if expires + c << "Domain=#{domain}" if domain + c << "Secure" if secure + c << "HttpOnly" if http_only + cookies << c.join("; ") end end end