require "../handler"
require "../views/html/page"
class Guff::Handlers::BlogHandler < Guff::Handler
ROUTES = [{
list: false,
blog: true,
re: %r{
^/
# match YYYY/MM/DD/SLUG.html
(?\d{4})
/
(?\d{2})
/
(?\d{2})
/
(?[a-z0-9._-]+)
\.html
$
}x,
}, {
list: true,
blog: true,
re: %r{
^/
# match YYYY/MM/DD
(?\d{4})
/
(?\d{2})
/
(?\d{2})
/?
$
}x,
}, {
list: true,
blog: true,
re: %r{
^/
# match YYYY/MM
(?\d{4})
/
(?\d{2})
/?
$
}x,
}, {
list: true,
blog: true,
re: %r{
^/
# match YYYY
(?\d{4})
/?
$
}x,
}, {
list: false,
blog: false,
re: %r{
^/
# match slug
(?[a-z0-9._-]+)
\.html
$
}x,
}, {
list: true,
blog: true,
re: %r{
# match index
^/$
}x,
}]
def call(context : HTTP::Server::Context)
path = context.request.path || ""
call_next(context) unless ROUTES.reduce(false) do |matched, route|
unless matched
if md = (route[:re] as Regex).match(path)
# log blog route match
puts "blog: route = %s, md = %s" % [
route.to_s,
md.to_s
]
# search for matching posts
posts = @models.post.get_posts(
filters: get_filters(md),
tags: [["foo"]],
)
if posts.size > 0
# mark as matched
matched = true
# draw result
draw(context, route, posts)
end
end
end
matched
end
end
FILTERS = {
year: "year",
month: "month",
day: "day",
slug: "slug",
}
private def get_filters(md) : Hash(Symbol, String)
FILTERS.reduce({} of Symbol => String) do |r, k, s|
r[k] = md[s] if md[s]?
r
end
end
private def draw(context, route, posts)
# create page
page = PageHTMLView.new("Posts", posts.rows.map { |post| post.to_s }.join)
# render page
context.response.content_type = page.content_type
context.response.puts page
end
end