Debian Codegraph @

R/parse_headers.R

raw
1 #' Parse response headers
2 #'
3 #' Parse response header data as returned by curl_fetch, either as a set of strings
4 #' or into a named list.
5 #'
6 #' The parse_headers_list function parses the headers into a normalized (lowercase
7 #' field names, trimmed whitespace) named list.
8 #'
9 #' If a request has followed redirects, the data can contain multiple sets of headers.
10 #' When multiple = TRUE, the function returns a list with the response headers
11 #' for each request. By default it only returns the headers of the final request.
12 #'
13 #' @param txt raw or character vector with the header data
14 #' @param multiple parse multiple sets of headers separated by a blank line. See details.
15 #' @export
16 #' @rdname parse_headers
17 #' @examples req <- curl_fetch_memory("https://hb.cran.dev/redirect/3")
18 #' parse_headers(req$headers)
19 #' parse_headers(req$headers, multiple = TRUE)
20 #'
21 #' # Parse into named list
22 #' parse_headers_list(req$headers)
23 parse_headers <- function(txt, multiple = FALSE){
24 if(!length(txt))
25 return(NULL)
26 if(is.raw(txt)){
27 txt <- rawToChar(txt)
28 }
29 stopifnot(is.character(txt))
30 if(length(txt) > 1){
31 txt <- paste(txt, collapse = "\n")
32 }
33
34 # Allow for either "\r\n" line breaks or just "\r" or "\n" (i.e. windows servers)
35 sets <- strsplit(txt, "\\r\\n\\r\\n|\\n\\n|\\r\\r")[[1]]
36 headers <- strsplit(sets, "\\r\\n|\\n|\\r")
37 if(multiple){
38 headers
39 } else {
40 headers[[length(headers)]]
41 }
42 }
43
44 #' @export
45 #' @rdname parse_headers
46 parse_headers_list <- function(txt){
47 headers <- grep(":", parse_headers(txt), fixed = TRUE, value = TRUE)
48 out <- lapply(headers, split_string, ":")
49 names <- tolower(vapply(out, `[[`, character(1), 1)) #names are case insensitive
50 values <- lapply(lapply(out, `[[`, 2), trimws)
51 names(values) <- names
52 values
53 }