爲每一個片斷添加惟一 id,併爲 /snippets 添加一個 DELETE http 動詞,以容許經過身份認證的用戶刪除本身的片斷。post
首先爲每一個片斷添加惟一 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