13-http/01-serve-one-response.protos

Repository
guillermomolina/protos
Commit
2723a55555e7beecee0816bf99d16e3c8c1ae635
Tree
c36054e4e5abd7fc29a039b4e096cac2e8706492
Blob
10d0ae534f876e032df0fcf9d754d01cfe0651be
Source
View exact source on GitHub
// THE LICENSED WORK IS PROVIDED UNDER THE TERMS OF THE ADAPTIVE PUBLIC LICENSE
// ("LICENSE") AS FIRST COMPLETED BY: Guillermo Adrián Molina. ANY USE, PUBLIC
// DISPLAY, PUBLIC PERFORMANCE, REPRODUCTION OR DISTRIBUTION OF, OR PREPARATION OF
// DERIVATIVE WORKS BASED ON, THE LICENSED WORK CONSTITUTES RECIPIENT'S ACCEPTANCE
// OF THIS LICENSE AND ITS TERMS, WHETHER OR NOT SUCH RECIPIENT READS THE TERMS OF
// THE LICENSE. "LICENSED WORK" AND "RECIPIENT" ARE DEFINED IN THE LICENSE. A COPY
// OF THE LICENSE IS LOCATED IN THE TEXT FILE ENTITLED "LICENSE.TXT" ACCOMPANYING
// THE CONTENTS OF THIS FILE. IF A COPY OF THE LICENSE DOES NOT ACCOMPANY THIS
// FILE, A COPY OF THE LICENSE MAY ALSO BE OBTAINED AT THE FOLLOWING WEB SITE:
// https://github.com/guillermomolina/protos
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
// the specific language governing rights and limitations under the License.

// Server.serveOne processes exactly one HTTP/1.1 request on a duplex you
// supply. It never listens on a port, so this lesson uses an in-memory duplex
// and runs under the standalone CLI.

http: import("std:http/server")
MemoryDuplex: import("./memory-duplex.protos")

duplex: MemoryDuplex.of("GET /hello?name=Protos HTTP/1.1\r\nHost: localhost\r\n\r\n")

// The handler receives exactly one Request object. The method and version
// are Strings; the target and every header value are raw Bytes.
handler: (request) => {
    print(request.method)
    print(Encoding.Latin1.decode(request.target))
    print(request.version)
    print(request.headers[0][0])

    // A Response is an ordinary object. Header values and the body are Bytes,
    // never Strings. The server adds Content-Length and Connection itself.
    response: {
        status: 200
        headers: [["Content-Type", Encoding.Latin1.encode("text/plain; charset=utf-8")]]
        body: Encoding.UTF8.encode("Hello from Protos")
    }
    response
}

// serveOne answers a Future that resolves to null once the response has been
// written and the session has retired. Waiting for it is up to the caller.
http.Server.serveOne(duplex, handler, null).value()

print(duplex.written())

// The borrowed variant never closes the duplex: closing it is still the
// caller's job. Server.serveOne.owning would have released it.
print(duplex.releaseCount())