Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Rails know when to respond with 304 status?

Given I have rails controller which accesses DB to retrieve data and render JSON response using serializer, what conditions must be met to make rails respond with 304?

If it has to compare previous response to currently retrieved, what kind of comparison is it?

like image 217
antiplayer Avatar asked Mar 24 '17 13:03

antiplayer


People also ask

What does the HTTP status code 304 indicate?

The HTTP 304 Not Modified client redirection response code indicates that there is no need to retransmit the requested resources. It is an implicit redirection to a cached resource.

Does a 304 response generally contain a message body?

The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.

What does head do in Rails?

In Rails, the head method is shorthand for "respond only with this status, headers, and an empty body." The head method takes a symbol corresponding to a status, in this case :no_content for "204."


1 Answers

The magic happens in Rack::ETag and Rack::ConditionalGet. (Mine are located at $GEM_HOME/rack-1.5.5/lib/rack/conditionalget.rb and $GEM_HOME/rack-1.5.5/lib/rack/etag.rb.)

These are middlewares.

Rack::ETag makes a digest out of the body (the very same body which gets returned by the rack function @app.call) and sets the response ETag header to this value. For Rails 4.0, at least, it's an MD5 hex digest.

Rack::ConditionalGet compares the request's If-None-Match header against the response's ETag header. If they match, then it returns a 304.

like image 113
JellicleCat Avatar answered Sep 30 '22 10:09

JellicleCat