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.
"/ws"] = function(stream)
app.get[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
variablesend
function Bonsai.write(
::HTTP.Stream,
stream::Template
template
)= Mustache.render(template.content, template.variables)
s write(s,
Bonsai.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)
= Bonsai.read(stream, Body(DataFrame))
df end
Writing a DataFrame
as CSV’s
using Bonsai, HTTP, DataFrames, CSV
function Bonsai.write(stream::HTTP.Stream, df::DataFrame)
= IOBuffer()
io write(io, df)
CSV.= String(take!(io))
data write(
Bonsai.
stream,Body(data),
Headers(
="text/csv",
content_type
)
)end
Writing a DataFrame
as JSON
using Bonsai, HTTP, DataFrames, Tables
function Bonsai.write(stream::HTTP.Stream, df::DataFrame)
write(
Bonsai.
stream,Body(Tables.rowtable(df)),
# Body(Tables.columntable(df)),
Headers(
="application/json",
content_type
)
)end