ktor HTTP API exercises

Exercise 1

Question

Add to each segment a unique id, and add a DELETE http verbs / snippets, to allow users to delete their own authentication fragment.

Answer

Start by adding a unique id for each segment:

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")
    )
)

New modified fragment post requests:

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))
                }
            }

Request to test the new fragment is normal, ID right

to add delete request to delete segment:

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"))
                    }
                }
            }

Add a DELETE HTTP request tests

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

Returned the following results, id for the snippets 1 has been deleted

Guess you like

Origin www.cnblogs.com/shy-/p/11456450.html