Skip to contents

These functions provide generic HTTP response messages based on the HTTP response status codes.

Usage

http_error(status = 500L, message = NULL)

http_success(status = 200L, message = NULL, body = NULL)

http_response(status = 200L, message = NULL, body = NULL)

http_handler(req, res, status = 200L, message = NULL, body = NULL)

Arguments

status

HTTP status code.

message

An HTTP response message or NULL. A generic response message is provided when it is NULL based on http_status_codes.

body

A list, additional values to be returned.

req

The request object.

res

The response object.

Value

http_error returns an error with a custom condition attribute after checking if the status code is at least 400.

http_success returns a list but checks that the status code is <400.

http_response returns a list checking only that the status code is valid.

http_handler behaves like http_response but it also sets the status code and the body of the response object.

Examples

try(http_error())
#> Error : Internal Server Error
try(http_error(400))
#> Error : Bad Request
try(http_error(400, "Sorry"))
#> Error : Bad Request - Sorry

str(http_success())
#> List of 3
#>  $ category: 'scalar' chr "Successful"
#>  $ status  : 'scalar' int 200
#>  $ message : 'scalar' chr "OK"
#>  - attr(*, "class")= chr [1:2] "http_success" "http_response"
str(http_success(201))
#> List of 3
#>  $ category: 'scalar' chr "Successful"
#>  $ status  : 'scalar' int 201
#>  $ message : 'scalar' chr "Created"
#>  - attr(*, "class")= chr [1:2] "http_success" "http_response"
str(http_success(201, "Awesome"))
#> List of 3
#>  $ category: 'scalar' chr "Successful"
#>  $ status  : 'scalar' int 201
#>  $ message : 'scalar' chr "Created - Awesome"
#>  - attr(*, "class")= chr [1:2] "http_success" "http_response"

str(http_response(201, "Awesome", list(name = "Jane", count = 6)))
#> List of 4
#>  $ category: 'scalar' chr "Successful"
#>  $ status  : 'scalar' int 201
#>  $ message : 'scalar' chr "Created - Awesome"
#>  $ body    :List of 2
#>   ..$ name : chr "Jane"
#>   ..$ count: num 6
#>  - attr(*, "class")= chr [1:2] "http_response" "list"

req <- new.env()
res <- new.env()
str(http_handler(req, res, 201, "Awesome", list(name = "Jane", count = 6)))
#> List of 4
#>  $ category: 'scalar' chr "Successful"
#>  $ status  : 'scalar' int 201
#>  $ message : 'scalar' chr "Created - Awesome"
#>  $ body    :List of 2
#>   ..$ name : chr "Jane"
#>   ..$ count: num 6
#>  - attr(*, "class")= chr [1:2] "http_response" "list"
res$status
#> [1] 201
str(res$body)
#> List of 4
#>  $ category: 'scalar' chr "Successful"
#>  $ status  : 'scalar' int 201
#>  $ message : 'scalar' chr "Created - Awesome"
#>  $ body    :List of 2
#>   ..$ name : chr "Jane"
#>   ..$ count: num 6
#>  - attr(*, "class")= chr [1:2] "http_response" "list"