Something went wrong. Try again.
My own corner of monopam
Something went wrong. Try again.
2.1 kB · 70 lines
OCaml
at main
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071type t = [ `Identity | `Gzip | `Deflate | `Compress | `Br | `Zstd ]
let of_string s = match String.lowercase_ascii s with | "identity" -> Some `Identity | "gzip" | "x-gzip" -> Some `Gzip | "deflate" -> Some `Deflate | "compress" | "x-compress" -> Some `Compress | "br" -> Some `Br | "zstd" -> Some `Zstd | _ -> None
let to_string : t -> string = function | `Identity -> "identity" | `Gzip -> "gzip" | `Deflate -> "deflate" | `Compress -> "compress" | `Br -> "br" | `Zstd -> "zstd"
let pp ppf c = Format.pp_print_string ppf (to_string c)let equal (a : t) (b : t) = a = b
type range = Any | Coding of ttype accept = (range * int) list
(* RFC 9110 s.12.5.3: a weighted list of codings, "*" for any other. *)let range_of_token = function | "*" -> Some Any | name -> Option.map (fun c -> Coding c) (of_string name)
let accept_of_string s = Http_weighted.of_string range_of_token s
let quality (a : accept) (c : t) = let named = List.find_map (function Coding c', w when equal c c' -> Some w | _ -> None) a in match named with | Some w -> w | None -> ( match List.find_map (function Any, w -> Some w | _ -> None) a with | Some w -> w | None -> if equal c `Identity then 1 else 0)
let negotiate headers offered = match Headers.all `Accept_encoding headers with | [] -> Some `Identity | fields -> ( match accept_of_string (String.concat "," fields) with | None -> Some `Identity | Some a -> let candidates = List.fold_left (fun acc c -> if equal c `Identity || List.exists (equal c) acc then acc else c :: acc) [] offered |> List.rev in let best, w = List.fold_left (fun (best, bw) c -> let w = quality a c in if w > bw then (c, w) else (best, bw)) (`Identity, -1) (candidates @ [ `Identity ]) in if w > 0 then Some best else None)