Skip to content

Instantly share code, notes, and snippets.

@dengyunsheng250
Created March 18, 2024 13:07
Show Gist options
  • Save dengyunsheng250/3e8603477734995a585bdc7be1a1e653 to your computer and use it in GitHub Desktop.
Save dengyunsheng250/3e8603477734995a585bdc7be1a1e653 to your computer and use it in GitHub Desktop.
Rust题目解答
use regex::Regex;
use std::collections::HashMap;
use std::fs;
fn main() {
let content = read();
let re = Regex::new(r#"^(?P<ip>\S+) \S+ \S+ \[(?P<timestamp>[^\]]+)\] "(?P<method>\S+) (?P<path>[^\s]+) \S+" (?P<status>\d+) \d+ "(?P<referrer>[^"]*)" "(?P<user_agent>[^"]*)"$"#).unwrap();
let mut mac = HashMap::new();
let mut linux = HashMap::new();
let mut win = HashMap::new();
let mut other = HashMap::new();
for line in content.lines() {
let caps = re.captures(line);
let caps = match caps {
Some(c) => c,
None => {
// 中文的请求默认不解析
continue;
}
};
let user_agent = &caps["user_agent"];
let user_agent = user_agent.to_string();
// 获得了操作系统和浏览器的信息
let lparen = user_agent.find('(');
let rparen = user_agent.find(')');
if rparen.is_none() || rparen.unwrap() + 1 >= user_agent.len() {
continue;
}
if !lparen.is_none() && !rparen.is_none() {
let os = &user_agent[lparen.unwrap() + 1..rparen.unwrap()];
let browser = &user_agent[rparen.unwrap() + 2..];
match os {
c if c.contains("Mac") => {
*mac.entry(browser.to_string()).or_insert(0) += 1;
}
c if c.contains("Windows") => {
*win.entry(browser.to_string()).or_insert(0) += 1;
}
c if c.contains("Linux") => {
*linux.entry(browser.to_string()).or_insert(0) += 1;
}
_ => {
*other.entry(browser.to_string()).or_insert(0) += 1;
}
}
}
}
let (k, v) = mac
.iter()
.max_by_key(|(_, &value)| value)
.expect("hashmap is empty");
println!("mac {}", k);
let (k, v) = win
.iter()
.max_by_key(|(_, &value)| value)
.expect("hashmap is empty");
println!("win {}", k);
let (k, v) = linux
.iter()
.max_by_key(|(_, &value)| value)
.expect("hashmap is empty");
println!("linux {}", k);
let (k, v) = other
.iter()
.max_by_key(|(_, &value)| value)
.expect("hashmap is empty");
println!("other {}", k);
}
//
// regex提取信息
// 考虑map-reduce进行优化
fn read() -> String {
fs::read_to_string("access.log").unwrap()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment