How do I get Hummingbird to serve html dynamically?
This article is part of a series.
Most the examples so far focus on returning data or simple strings, but what if instead I wanted an actual HTML response generated programmatically?
This post will show simply wrapping a string of known-good HTML and in a response. The next post using a Mustache template. The combined example is available:
OrganPlayerHTML.swift
I snagged the html string -> http response wrapper code for this from the hummingbird examples repo, but made it a type that would accept a “message” String.
import Hummingbird
struct OrganPlayerHTML: ResponseGenerator {
let message: String
init(_ message: String) {
self.message = message
}
private var html:String {
Self.generateHTMLForMessage(message)
}
func response(from request: Request, context: some RequestContext) throws -> Response {
let buffer = ByteBuffer(string: self.html)
return .init(status: .ok, headers: [.contentType: "text/html"], body: .init(byteBuffer: buffer))
}
static func generateHTMLForMessage(_ message:String) -> String {
"""
<!DOCTYPE html>
<html>
<head>
<title>Hear the Music!!!</title>
<meta charset="UTF-8">
</head>
<body>
<p>\(message)</p>
<p><a href="/">back to index</a>.</p>
</body>
</html>
"""
}
}
The Route
Back in the buildRouter
function in Application+build.swift
one possible route one could use could be:
router.get("organ/:message") { _, context in
guard let message = context.parameters.get("message", as: String.self) else {
throw HTTPError(.badRequest, message:"Could not parse message.")
}
return OrganPlayerHTML(message)
}
Don’t forget to percent encode any spaces, etc.…
The Call
In the public folders’s index HTML page a call to that route might look like
<body>
<li>These links return generated HTML pages as their response bodies</li>
<ul>
<li><a href=/organ/LaTaDadaDadaLaTaDaDah>organ music</a></li>
</ul>
</li>
</body>
Tada!
Not the most snazzy, but I hope it points to how to use a Hummingbird route to trigger building a simple HTML page for more complicated examples.
There are MANY swift packages where people create their favorite way to generate HTML, if the situation is too complex to handle by hand.
For me my preference would be the Mustache templating engine, which conveniently the Hummingbird Project already has covered.
Next post!