HTTP
Almost every program talks to another over HTTP. This lesson builds a tiny web server and a web client in one program, so you can see both sides of the conversation.
What you will learn#
- what HTTP requests and responses are,
- a web server whose addresses are Ring functions,
- a web client with
HttpClient, - why requests are asynchronous and what a
Taskis, - status codes.
HTTP in one minute#
A client sends a request: a method (GET to read, POST to send data, DELETE to remove), an address, optional data. The server sends a response: a status code (200 OK, 201 Created, 404 Not Found, 500 error) and a body (text, HTML or JSON).
The program#
# HTTP - a web server and a web client in one program
load "dotnet.ring"
using {
"System.Net.Http"
"System.Threading.Tasks"
"RingDotNet.Web"
}
oServer = ""
oClient = ""
cUrl = ""
func main
# 1. A web server: a Ring function answers each address
oServer = new WebServer("http://127.0.0.1:0") # port 0: the system picks a free port
oServer.onGet("/hello","hello")
oServer.onGet("/time","clock")
oServer.onPost("/echo","echo")
cUrl = oServer.url()
? "The server listens at " + cUrl
# 2. A web client: HttpClient sends requests. Asking is asynchronous: it returns a Task
oClient = new HttpClient()
? nl + "GET /hello -> " + fetch("GET","/hello","")
? "GET /time -> " + fetch("GET","/time","")
? "POST /echo -> " + fetch("POST","/echo","some data")
? "GET /nothing-> " + fetch("GET","/nothing","")
oServer.close()
# The handlers: each gets the request and returns the answer
func hello oRequest
return "Hello from a Ring handler"
func clock oRequest
return webJson([["hour",12],["minute",30]])
func echo oRequest
return [201,"text/plain","you sent: " + oRequest.body()]
# Send one request and return the answer. The server runs on .NET threads, but Ring code may only run on the Ring thread:
# serveOne() hands one waiting request to its Ring handler.
func fetch cMethod, cPath, cBody
if cMethod = "GET"
oTask = oClient.GetAsync(cUrl + cPath)
else
oContent = new StringContent(cBody)
oTask = oClient.PostAsync([ :requestUri = cUrl + cPath, :content = oContent ])
ok
for nTry = 1 to 50
if oServer.serveOne(100)
exit
ok
next
oTask.Wait(NULL)
oResponse = oTask.Result
oBody = oResponse.Content.ReadAsStringAsync(NULL)
oBody.Wait(NULL)
return oResponse.StatusCode + " " + oBody.ResultThe server listens at http://127.0.0.1:50441
GET /hello -> OK Hello from a Ring handler
GET /time -> OK {"hour":12,"minute":30}
POST /echo -> Created you sent: some data
GET /nothing-> NotFound Not found: GET /nothingThe port number is chosen by the system, so it differs on every run.
How it works#
The server#
using { ..., "RingDotNet.Web" } (first!) starts the ASP.NET Core runtime. new WebServer("http://127.0.0.1:0") starts a server on your computer (127.0.0.1 is "this computer"); port 0 means "any free port", and oServer.url() tells you which one.
Each address is connected to a Ring function with onGet, onPost, onDelete. The function receives the request and returns the answer:
| The handler returns | The response |
|---|---|
| a text | status 200, the text as HTML |
[status, contentType, text] | exactly that |
webJson(list) | status 200, JSON |
A path that has no handler answers 404 Not found.
The client#
HttpClient.GetAsync(url) sends a GET; PostAsync([ :requestUri = url, :content = content ]) sends data. These methods are asynchronous: they return at once with a Task, an object that stands for "the answer will come". Wait(NULL) waits for it, and its property Result is the answer (the response). The body is also asynchronous: ReadAsStringAsync(NULL) is another Task.
Why serveOne#
The web server runs on .NET's own threads, but your Ring code may only run on the Ring thread. The server therefore puts each request in a queue, and oServer.serveOne(100) takes one request off the queue — waiting up to 100 ms — and runs your handler on the Ring thread. Here client and server are in the same program, so while the client waits, the program calls serveOne. A real server just calls oServer.run(), which serves until stop().
Status codes#
oResponse.StatusCode is an enum, so Ring gets the text OK, Created, NotFound. 201 Created is the right answer when a POST made something new.
What you learned#
- requests have a method, an address and maybe a body; responses have a status and a body,
- handlers return text,
[status, type, text]orwebJson, - asynchronous calls return a
Task: wait, then readResult, serveOne()hands requests to Ring.
Exercises#
- Add a
/hellovariant/hello?name=Annthat returnsHello, Ann. (oRequest.query("name").) - Make
/timereturn the real time withDateTime.Now. - Add a
DELETE /itemhandler that answers404for unknown items. - Call a real web site:
oClient.GetStringAsync("https://example.com")and print the length of the answer (needs internet).