pub fn parse_sections(input: &str) -> Result<Vec<Section<'_>>, Error<'_>>
Expand description

Parse a string representing a haproxy config to list of sections. Preservers comments and the order of the sections and their options. Unknown sections will result in multiple UnknownLine entries.

You can build a more strongly typed Config struct from the output, see example below.

Examples

use haproxy_config::parse_sections;
use haproxy_config::Config;

let file = include_str!("../tests/medium_haproxy.cfg");
let sections = parse_sections(file).unwrap();

// Build a config from the sections
let config = Config::try_from(sections.as_slice()).unwrap();
Examples found in repository?
examples/ports.rs (line 11)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
fn main() {
    let path = env::args()
        .nth(1)
        .expect("need the path to the haproxy cfg file");
    let config = read_to_string(&path).expect("haproxy config file needs to be readable");
    let sections = parse_sections(config.as_str())
        .map_err(|e| e.with_path(path))
        .unwrap();
    println!("{sections:#?}");
    let config: config::Config = sections.as_slice().try_into().unwrap();
    println!("{config:#?}");

    let frontend_ports = config.frontends.values().map(|f| f.bind.addr.port);
    let listen_ports = config.listen.values().map(|f| f.bind.addr.port);
    let ports: Vec<_> = frontend_ports.chain(listen_ports).collect();
    println!("ports bound to by haproxy: {ports:?}")
}