Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Query based routing (continuation of #39) #81

Merged
merged 2 commits into from
Mar 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/routing.jl
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using HTTP

export method, GET, route, page, probabilty
export method, GET, route, page, probabilty, query

# Request type

Expand Down Expand Up @@ -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()<x, app...)
18 changes: 17 additions & 1 deletion test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@ using Mux
using Test
using Lazy
using HTTP
import HTTP.ExceptionRequest: StatusError

@test Mux.notfound()(d())[:status] == 404

d1 = Dict("one"=> "1", "two"=> "2")
d2 = Dict("one"=> "1", "two"=> "")
# Test basic server
@app test = (
Mux.defaults,
page("/",respond("<h1>Hello World!</h1>")),
page("/about", respond("<h1>Boo!</h1>")),
page("/user/:user", req -> "<h1>Hello, $(req[:params][:user])!</h1>"),
query(d1, respond("<h1>query1</h1>")),
query(d2, respond("<h1>query2</h1>")),
Mux.notfound())
serve(test)
@test String(HTTP.get("http://localhost:8000").body) ==
Expand All @@ -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) ==
"<h1>query1</h1>"
@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) ==
"<h1>query2</h1>"
@test String(HTTP.get("http://localhost:8000/dum?one=1&two=hfjd").body) ==
"<h1>query2</h1>"
@test_throws StatusError String(HTTP.get("http://localhost:8000/dum?one=1&two=2&sarv=boo").body)