Created
September 7, 2016 11:19
-
-
Save pyldin601/b38f6298ca7c7c17cbaf763dd04ff5a6 to your computer and use it in GitHub Desktop.
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
package biz.radioteria.web.server | |
import biz.radioteria.web.request.Request | |
import biz.radioteria.web.request.RequestMethod | |
import com.sun.net.httpserver.HttpExchange | |
fun fromHttpExchange(httpExchange: HttpExchange): Request { | |
val method = httpExchange.requestMethod | |
val path = normalizedRequestPath(httpExchange.requestURI.path) | |
val query = httpExchange.requestURI.query ?: "" | |
return Request(RequestMethod.valueOf(method), path, queryStringToMap(query)) | |
} | |
fun queryStringToMap(queryString: String): Map<String, String> { | |
if (queryString.isNullOrBlank()) { | |
return mapOf() | |
} | |
return queryString.split("&").fold(emptyMap()) { | |
map, item -> map + hashMapOf(item.splitAt("=")) | |
} | |
} | |
fun normalizedRequestPath(requestPath: String): String { | |
return if (requestPath.equals("/")) requestPath else requestPath.substring(1) | |
} | |
fun String.splitAt(substring: String): Pair<String, String> { | |
with(this.split(substring, limit = 2)) { | |
return if (this.size < 2) Pair(this[0], "") else Pair(this[0], this[1]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment