HTTP Programming

HTTP is a general application layer protocol which realizes data transfer through a request-response mechanism. The client sends a request and the server returns a response. Both the request and response contains a packet header and a packet body.

GET and POST are two common request types. The former request contains only a packet header and is used to request application-layer data from a server. The latter request has a packet body, which is separated from the header by a blank line. It provides application-layer data for the server.

The packet headers of requests and responses contain many fields, which are not described here. Cangjie supports HTTP 1.0, 1.1, and 2.0 and other versions. You can construct requests and response packets based on the RFC 9110, 9112, 9113, 9218, and 7541 protocols, as well as HttpRequestBuilder and HttpResponseBuilder provided by Cangjie.

The following example shows how to use Cangjie for client and server programing. The client sends a request whose header is "GET /hello" and the server returns a response whose body is "Hello Cangjie!" The code is as follows:

import net.http.*
import std.time.*
import std.sync.*
import std.log.LogLevel

// 1. Construct a server instance.
let server = ServerBuilder()
    .addr("127.0.0.1")
    .port(8080)
    .build()

func startServer(): Unit {
    // 2. Register with the request processing logic.
    server.distributor.register("/hello", {httpContext =>
        httpContext.responseBuilder.body("Hello Cangjie!")
    })
    server.logger.level = OFF
    // 3. Start the service.
    server.serve()
}

func startClient(): Unit {
    // 1. Construct a client instance.
    let client = ClientBuilder().build()
    // 2. Send a request.
    let response = client.get("http://127.0.0.1:${server.port}/hello")
    // 3. Read the response.body
    let buffer = Array<Byte>(32, item: 0)
    let length = response.body.read(buffer)
    println(String.fromUtf8(buffer[..length]))
    // 4. Close the connection.
    client.close()
}

main () {
    spawn {
        startServer()
    }
    sleep(Duration.second)
    startClient()
}

Compiling and executing the preceding code will display the following information:

Hello Cangjie!