diff --git a/src/routing.jl b/src/routing.jl index 0240faf7..e00ec972 100644 --- a/src/routing.jl +++ b/src/routing.jl @@ -1,6 +1,6 @@ using HTTP -export method, GET, route, page, probabilty +export method, GET, route, page, probabilty, query # Request type @@ -44,6 +44,24 @@ page(p::AbstractString, app...) = page(splitpath(p), app...) page(app...) = page([], app...) page(app::Function, p) = page(p, app) +# Query routing + +function matchquery(q, req) + qdict = HTTP.URIs.queryparams(req[:query]) + length(q) != length(qdict) && return false + for (key, value) in q + if haskey(qdict, key) && (value == "" || value == qdict[key]) + continue + else + return false + end + end + return true +end + +query(q::Dict{<:AbstractString, <:AbstractString}, app...) = + branch(req -> matchquery(q, req), app...) + # Misc probabilty(x, app...) = branch(_->rand() "1", "two"=> "2") +d2 = Dict("one"=> "1", "two"=> "") # Test basic server @app test = ( Mux.defaults, page("/",respond("

Hello World!

")), page("/about", respond("

Boo!

")), page("/user/:user", req -> "

Hello, $(req[:params][:user])!

"), + query(d1, respond("

query1

")), + query(d2, respond("

query2

")), Mux.notfound()) serve(test) @test String(HTTP.get("http://localhost:8000").body) == @@ -30,3 +34,15 @@ function f() end @test f() == nothing + +# Query based routing +@test String(HTTP.get("http://localhost:8000/dum?one=1&two=2").body) == + "

query1

" +@test_throws StatusError String(HTTP.get("http://localhost:8000/dum?one=1").body) +@test_throws StatusError String(HTTP.get("http://localhost:8000/dum?one=1&two=2&sarv=boo").body) +@test_throws StatusError String(HTTP.get("http://localhost:8000/dum?one=1").body) +@test String(HTTP.get("http://localhost:8000/dum?one=1&two=56").body) == + "

query2

" +@test String(HTTP.get("http://localhost:8000/dum?one=1&two=hfjd").body) == + "

query2

" +@test_throws StatusError String(HTTP.get("http://localhost:8000/dum?one=1&two=2&sarv=boo").body)