parser: regenerate with lambda
[nit.git] / lib / app / http_request.nit
index 80c6d8b..07d4bf3 100644 (file)
 # limitations under the License.
 
 # HTTP request services: `AsyncHttpRequest` and `Text::http_get`
+#
+# ~~~nitish
+# import app::http_request
+#
+# class MyHttpRequest
+#     super AsyncHttpRequest
+#
+#     redef fun uri do return "http://example.com/"
+#
+#     redef fun on_load(data, status) do print "Received: {data or else "null"}"
+#
+#     redef fun on_fail(error) do print "Connection error: {error}"
+# end
+#
+# var req = new MyHttpRequest
+# req.start
+# ~~~
 module http_request
 
 import app_base
 import pthreads
-import json::serialization
+import json
 
 import linux::http_request is conditional(linux)
 import android::http_request is conditional(android)
@@ -122,6 +139,28 @@ abstract class AsyncHttpRequest
        fun after do end
 end
 
+# Simple `AsyncHttpRequest` where `uri` is an attribute
+#
+# Prints on communication errors and when the remote server returns an
+# HTTP status code not in the 200s.
+#
+# This class can be instantiated to execute a request where the response is
+# ignored by the application. Alternatively, it can be subclassed to implement
+# `on_load`.
+#
+# ~~~nitish
+# var request = new SimpleAsyncHttpRequest("http://example.com")
+# request.start
+# ~~~
+class SimpleAsyncHttpRequest
+       super AsyncHttpRequest
+
+       redef var uri
+
+       redef fun on_load(data, status) do if status < 200 or status >= 299
+       then print_error "HTTP request '{uri}' received HTTP status code: {status}"
+end
+
 redef class Text
        # Execute an HTTP GET request synchronously at the URI `self`
        #