Examples

Bellow are various examples and short snippets of code.

Web Sockets

A web sockets can be obtained using ws_upgrade, bellow is an example of a echo socket.

app.get["/ws"] = function(stream)
    ws_upgrade(stream) do ws
        for msg in ws
            @info msg
            send(ws, msg)
        end
    end
end

Mustache

We can overload Bonsai.write to do the correct thing for our templates.

using Bonsai, HTTP, Mustache, Dates

struct Template
    content
    variables
end

function Bonsai.write(
    stream::HTTP.Stream,
    template::Template
)
    s = Mustache.render(template.content, template.variables)
    Bonsai.write(s, 
            Body(s),
            Headers(content_type = "text/html; charset=UTF-8")
    )
end

DataFrames

Reading CSV’s from a request body as a DataFrame.

using DataFrames, CSV

function Bonsai.read(stream::HTTP.Stream, ::Body{DataFrame})
    return CSV.read(stream.message.body, DataFrame)
end

function handler(stream)
    df = Bonsai.read(stream, Body(DataFrame))
end

Writing a DataFrame as CSV’s

using Bonsai, HTTP, DataFrames, CSV

function Bonsai.write(stream::HTTP.Stream, df::DataFrame)
    io = IOBuffer()
    CSV.write(io, df)
    data = String(take!(io))
    Bonsai.write(
        stream,
        Body(data),
        Headers(
            content_type="text/csv",
        )
    )
end

Writing a DataFrame as JSON


using Bonsai, HTTP, DataFrames, Tables

function Bonsai.write(stream::HTTP.Stream, df::DataFrame)
    Bonsai.write(
        stream,
        Body(Tables.rowtable(df)),
        # Body(Tables.columntable(df)),
        Headers(
            content_type="application/json",
        )
    )
end