examples: annotate examples
[nit.git] / lib / nitcorn / http_response.nit
index 523c051..ec83289 100644 (file)
 # Provides the `HttpResponse` class and `http_status_codes`
 module http_response
 
+import serialization
+
 # A response to send over HTTP
 class HttpResponse
+       serialize
 
        # HTTP protocol version
        var http_version = "HTTP/1.0" is writable
@@ -37,16 +40,40 @@ class HttpResponse
        # Body of this response
        var body = "" is writable
 
+       # Files appended after `body`
+       var files = new Array[String]
+
        # Finalize this response before sending it over HTTP
        fun finalize
        do
                # Set the content length if not already set
                if not header.keys.has("Content-Length") then
-                       header["Content-Length"] = body.bytelen.to_s
+                       # Size of the body
+                       var len = body.byte_length
+
+                       # Size of included files
+                       for path in files do
+                               # TODO handle these error cases elsewhere, an error here will result in an invalid response
+                               if not path.file_exists then
+                                       print_error "File does not exists at '{path}'"
+                                       continue
+                               end
+
+                               var stat = path.file_stat
+                               if stat == null then
+                                       print_error "Failed to stat file at '{path}'"
+                                       continue
+                               end
+
+                               len += stat.size
+                       end
+
+                       # Set header
+                       header["Content-Length"] = len.to_s
                end
 
                # Set server ID
-               if not header.keys.has("Server") then header["Server"] = "unitcorn"
+               if not header.keys.has("Server") then header["Server"] = "nitcorn"
        end
 
        # Get this reponse as a string according to HTTP protocol
@@ -73,7 +100,8 @@ class HttpStatusCodes
        # All know code and their message
        var codes = new HashMap[Int, String]
 
-       protected init do insert_status_codes
+       # Init the status `codes` list.
+       protected init is old_style_init do insert_status_codes
 
        # Get the message associated to the status `code`, return `null` in unknown
        fun [](code: Int): nullable String