首页 > Windows开发 > 详细

ktor HTTP API 练习

时间:2019-09-04 00:07:46      阅读:110      评论:0      收藏:0      [点我收藏+]

练习一

Question

为每个片段添加唯一 id,并为 /snippets 添加一个 DELETE http 动词,以允许通过身份认证的用户删除自己的片段。

Answer

首先为每个片段添加唯一 id:

data class Snippet(val id: Int, val user: String, val text: String)
val snippets = Collections.synchronizedList(
    mutableListOf(
        Snippet(id = 1, user = "test", text = "hello"),
        Snippet(id = 2, user = "test", text = "world")
    )
)

修改新增片段的post请求:

authenticate {
                post {
                    val post = call.receive<PostSnippet>()
                    val principal = call.principal<UserIdPrincipal>() ?: error("No principal")
                    snippets += Snippet(snippets.size+1, principal.name, post.snippet.text)
                    call.respond(mapOf("OK" to true))
                }
            }

先测试新增片段的请求是否正常,ID正确
技术分享图片
添加删除片段的delete请求:

authenticate {
                delete("/{id}") {
                    val id = call.parameters["id"]
                    val snip = snippets.find { s -> s.id == id?.toInt() }
                    if (snip != null) {
                        snippets.remove(snip)
                        call.respond(mapOf("snippets" to synchronized(snippets) { snippets.toList() }))
                    }
                    else{
                        call.respond(mapOf("msg" to "no such id"))
                    }
                }
            }

添加一个DELETE的HTTP请求测试

DELETE {{host}}/snippets/1
Authorization: Bearer {{auth_token}}

返回结果如下,id为1的snippets已被删除
技术分享图片

ktor HTTP API 练习

原文:https://www.cnblogs.com/shy-/p/11456450.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!