Created
August 22, 2017 07:50
-
-
Save s4nchez/bb6f69b07395846bf443a738c84cf71c to your computer and use it in GitHub Desktop.
A simple wrapper around utterlyidle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.googlecode.utterlyidle.* | |
import com.googlecode.utterlyidle.servlet.ApplicationServlet | |
import javax.servlet.http.HttpServlet | |
import javax.servlet.http.HttpServletRequest | |
import javax.servlet.http.HttpServletResponse | |
class Application(bindings: List<Binding>): HttpHandler { | |
val matcher = BindingMatcher(bindings = bindings) | |
override fun handle(request: Request): Response { | |
val binding = matcher.match(request) | |
return binding.action(request) | |
} | |
} | |
class BindingMatcher(val bindings: List<Binding>) { | |
private fun binding(method: String, path: String) = Binding(Method.valueOf(method), path, { request -> ResponseBuilder.response(Status.NOT_FOUND.description("Route not found")).build() }) | |
fun match(request: Request): Binding { | |
val binding: Binding? = bindings | |
.filter { binding -> binding.method.equals(Method.valueOf(request.method())) } | |
.find({ binding -> | |
val uriTemplate = UriTemplate.uriTemplate(binding.path) | |
uriTemplate.matches(request.uri().toString()) | |
}) | |
return binding ?: binding(request.method(), request.uri().path()) | |
} | |
} | |
class UtterlyIdleBindingBasedServlet(val application: Application) : HttpServlet() { | |
override fun service(req: HttpServletRequest?, resp: HttpServletResponse?) { | |
val request = ApplicationServlet.request(req) | |
ApplicationServlet.transfer(application.handle(request), resp) | |
} | |
} | |
enum class Method { | |
GET, POST, PUT | |
} | |
data class Binding(val method: Method, val path: String, val action: (Request) -> Response) | |
infix fun Pair<Method,String>.by(action: (Request)->Response) = Binding(first, second, action) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment