Skip to content

Instantly share code, notes, and snippets.

@kavan-mevada
Last active January 19, 2020 11:19
Show Gist options
  • Save kavan-mevada/282880b8efcaa4f1d1104f4127f97d10 to your computer and use it in GitHub Desktop.
Save kavan-mevada/282880b8efcaa4f1d1104f4127f97d10 to your computer and use it in GitHub Desktop.
enum class Type { STATUS, HEADER, BODY }
fun readK(fd: Int, chunk: Int, block: (ByteArray) -> Unit) {
var type = Type.STATUS
var contentLength = 0L
var spaceCount = 0
var method = ""; var path = ""; var protocol = ""
var key = ""; var value = ""
var isKey = true
val headers = hashMapOf<String, String>()
var endPoint = 0
loop@do {
val buffer= ByteArray(chunk)
// TODO Platform Specific
val length = read(fd, buffer.refTo(0), chunk.convert()).toInt()
if (type==Type.BODY) {
block(buffer)
contentLength-=length
if (contentLength<=0) break@loop
} else {
for (i in 0 until length) {
val char = buffer[i].toChar()
if (type == Type.STATUS) {
// Parse STATUS
when (char) {
'\n' -> type = Type.HEADER
' ' -> spaceCount++
else -> when {
spaceCount==0 -> method += char // Request
spaceCount==1 -> path += char // Request
spaceCount>1 -> protocol += char
}
}
} else when {
// Parse HEADER
char == '\n' -> {
if (key.isNotEmpty() && value.isNotEmpty()) {
if (contentLength<=0 && key == "Content-Length"){
contentLength=value.toLong()
}
headers[key] = value
}
key = "" // reset
isKey = true
}
char == ':' && isKey -> {
isKey = false
value = "" // reset
}
char != '\r' -> when {
isKey -> key += char
value.isEmpty() && char == ' ' -> {}
else -> value += char
}
}
if (char=='\r'||char=='\n') endPoint++ else endPoint=0
if (endPoint>3) {
if (contentLength>0) {
val tmpBuff = ByteArray(chunk)
// TODO Platform Specific
memcpy(tmpBuff.refTo(0), buffer.refTo(i+1), (chunk-(i+1L)).convert())
contentLength-=(chunk-(i+1L))
if (contentLength>0) {
// TODO Platform Specific
contentLength -= read(fd, tmpBuff.refTo(chunk - (i + 1)), (i + 1L).convert())
}
block(tmpBuff)
}
if (contentLength<=0) break@loop
else type = Type.BODY; break
}
}
}
} while (length > 0)
println("---------------")
println("$method $path $protocol")
println(headers)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment