59
A Kotlin/Ktor webserver prototype that receives a string and returns an encoded...
source link: https://gist.github.com/gcmartinelli/9b1d9c0a783e72e8471ed12cdccd1041
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
A Kotlin/Ktor webserver prototype that receives a string and returns an encoded string to be printed
Instantly share code, notes, and snippets.
A Kotlin/Ktor webserver prototype that receives a string and returns an encoded string to be printed - in color - by a terminal using curl
/* A prototype script that creates a webserver that receives a string and returns | |
an encoded string to be printed - in color - by a terminal using curl. | |
Dependency: Kotlin and Ktor (www.ktor.io) | |
*/ | |
import io.ktor.application.call | |
import io.ktor.response.respondBytes | |
import io.ktor.routing.get | |
import io.ktor.routing.routing | |
import io.ktor.server.engine.embeddedServer | |
import io.ktor.server.netty.Netty | |
fun main() { | |
/* Returns a bytestring of the value passed at the URL | |
e.g. "curl http://localhost:8000/yolo" prints "yolo " to the | |
console in red letters and white background. */ | |
val server = embeddedServer(Netty, port=8000) { | |
routing { | |
get("/{string}") { | |
val string = call.parameters["string"] ?: "" | |
call.respondBytes(addColor(string)) | |
} | |
} | |
} | |
server.start(wait = true) | |
} | |
fun addColor(string: String) : ByteArray { | |
/* Concatenates the string with the necessary ANSI code for coloring (fixed colors for now) */ | |
val start = byteArrayOf(32, 27, 91, 51, 49, 59, 49, 48, 55, 109) // '\033[0;31m' > RED on WHITE BG | |
val end = byteArrayOf(32, 27, 91, 49, 48, 55, 109) // '\033[0m' > no color | |
val new_string = string.map { | |
it.toByte() // transform string into a byte array | |
} | |
var ret = start + new_string | |
ret += end | |
return ret | |
} |
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK