实现 DELETE
添加 DELETE 支持与添加 GET 支持的差别不大。但在这里,我仅需要通过 IATA 代码逐个删除机场。如果用户提交了一个不带有 IATA 代码的 HTTP DELETE 请求的话,我将返回一个 400 HTTP 状态码 Bad Request。如果用户提交了一个无法找到的 IATA 代码的话,我将返回一个常见的 404 状态码 Not Found。只有删除成功了,我才会返回标准的 200 OK(参见 参考资料,查看更多有关 HTTP 状态码的信息的链接)。
将清单 12 中的代码添加到 index 操作中的 DELETE case 中:
清单 12. 对 HTTP DELETE 做出响应
def index = {
switch(request.method){
case "POST": //...
case "GET": //...
case "PUT": //...
case "DELETE":
if(params.iata){
def airport = Airport.findByIata(params.iata)
if(airport){
airport.delete()
render "Successfully Deleted."
}
else{
response.status = 404 //Not Found
render "${params.iata} not found."
}
}
else{
response.status = 400 //Bad Request
render """DELETE request must include the IATA code
Example: /rest/airport/iata
"""
}
break
}
}
switch(request.method){
case "POST": //...
case "GET": //...
case "PUT": //...
case "DELETE":
if(params.iata){
def airport = Airport.findByIata(params.iata)
if(airport){
airport.delete()
render "Successfully Deleted."
}
else{
response.status = 404 //Not Found
render "${params.iata} not found."
}
}
else{
response.status = 400 //Bad Request
render """DELETE request must include the IATA code
Example: /rest/airport/iata
"""
}
break
}
}
首先,试着删除一个已知确实存在的机场,如清单 13 所示:
清单 13. 删除一个存在的机场
Deleting a Good Airport</heading>
$ curl --verbose --request DELETE http://localhost:9090/trip/rest/airport/lga
> DELETE /trip/rest/airport/lga HTTP/1.1
< HTTP/1.1 200 OK
Successfully Deleted.
$ curl --verbose --request DELETE http://localhost:9090/trip/rest/airport/lga
> DELETE /trip/rest/airport/lga HTTP/1.1
< HTTP/1.1 200 OK
Successfully Deleted.
然后,试着删除一个已知不存在的机场,如清单 14 所示:
清单 14. 试着 DELETE 一个不存在的机场
$ curl --verbose --request DELETE http://localhost:9090/trip/rest/airport/foo
> DELETE /trip/rest/airport/foo HTTP/1.1
< HTTP/1.1 404 Not Found
foo not found.
> DELETE /trip/rest/airport/foo HTTP/1.1
< HTTP/1.1 404 Not Found
foo not found.
最后,试着发出一个不带有 IATA 代码的 DELETE 请求,如清单 15 所示:
清单 15. 试着一次性 DELETE 所有机场
$ curl --verbose --request DELETE http://localhost:9090/trip/rest/airport
> DELETE /trip/rest/airport HTTP/1.1
< HTTP/1.1 400 Bad Request
DELETE request must include the IATA code
Example: /rest/airport/iata
> DELETE /trip/rest/airport HTTP/1.1
< HTTP/1.1 400 Bad Request
DELETE request must include the IATA code
Example: /rest/airport/iata