前言
mini-api是Kotlin写的,自然要加入一些Kotlin的特性,让代码更简洁,所以在最新的版本中,我们可以这样定义接口API。
引入
implementation 'com.houxinlin:mini-api:1.3.3'
fun main() {
val coolMini = CoolMini(8080)
coolMini.withKotlin {
get("test"){
val userName =getRequestParam("user")
setResult(userName.toString())
}
}
coolMini.start(Test::class.java)
}
这样,我们就定义了一个方法为GET的请求,地址为/test,同样,还可以通过Post、Put、Delete定义不同的Http请求类型,在后面的大括号中,是具体的处理逻辑,并且可通过getRequestParam等提供的方法获取一些参数。
返回至客户端可以通过setResult方法,但仅支持字符类型和字节类型,如果想返回某个对象的json形式,可以通过内置的方法toJson来完成,如下所示。
coolMini.withKotlin {
get("test"){
val userName =getRequestParam("user")
setResult(toJson(mutableMapOf("userName" to userName,"code" to "0")))
}
}
还可以直接通过httpRequest、httpResponse对象拿到请求、响应对象,并且通过他们使用session等功能。
数据库支持
支持基本的CRUD,方法还是同以前一样。
fun main() {
val coolMini = CoolMini(8080)
coolMini.withKotlin {
configDatabase {
userName="root"
password="hxl495594.."
url="jdbc:mysql://localhost:3306/db_inner"
}
get("test"){
var runSqlListMap = runSqlListMap("select * from tb_user")
setResult(toJson(runSqlListMap))
}
}
coolMini.start(Test::class.java)
}
同样也可以使用原来Mybatis的Mapper方式。
getMybatisCrudRepository().getMapper()