ktor HTTP API 练习

练习一

Question

为每一个片断添加惟一 id,并为 /snippets 添加一个 DELETE http 动词,以容许经过身份认证的用户删除本身的片断。post

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请求:code

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请求:blog

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请求测试token

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

返回结果以下,id为1的snippets已被删除
ip

相关文章
相关标签/搜索