分类 标签 存档 社区 订阅 搜索

2020-05-29 日志

0 浏览0 评论

structopt - 自定义解析方法

https://docs.rs/structopt/0.3.14/structopt/#custom-string-parsers

fn image_format_try_from_str(src: &str) -> Result<ImageFormat, String> {
    use ImageFormat::*;

    let choose: HashMap<&'static str, ImageFormat> = vec![
        ("png", Png),
        ("jpg", Jpeg),
        ("jpeg", Jpeg),
        ("gif", Gif),
        ("webp", WebP),
        ("pnm", Pnm),
        ("tiff", Tiff),
        ("tga", Tga),
        ("dds", Dds),
        ("bmp", Bmp),
        ("ico", Ico),
    ]
    .into_iter()
    .collect();

    let mut names = vec![];
    for (name, image_format) in choose {
        if name == src {
            return Ok(image_format);
        }
        names.push(name);
    }

    Err(format!("'{}' not one of '{}'", src, names.join("/")))
}

在结构体上:

#[derive(StructOpt, Debug)]
struct CliOptions {
    #[structopt(
        short="t",
        long,
        parse(try_from_str = image_format_try_from_str),
    )]
    output_format: ImageFormat,
}

即使输出类型在结构体里定义成 Option,也能正常工作。structopt 的做法充分利用了类型信息,是个值得学习的思路。

跨域和 OPTIONS 方法

当一个 HTTP 请求不是简单请求,即有自定义的头部信息,或 POST 的 Content-Type 不是 application/x-www-form-urlencodedtext/plainmultipart/form-data 之一,或当一个 HTTP 请求跨域,客户端可能先执行 OPTIONS 方法,用于请求获得由 Request-URI 标识的资源在请求/响应的通信过程中可以使用的功能选项,在采取具体资源请求之前,决定对该资源采取何种必要措施,或者了解服务器的性能。

logrotate

https://github.com/logrotate/logrotate

运行需要一个配置文件:

compress

/var/log/app/log.txt {
  rotate 8
  size 1M
}

它的意思是,/var/log/app/log.txt 这个文件,保存 8 个历史记录,每个至多 1MB。而历史日志需要压缩。用下面的方式运行它。

logrotate -s status.txt config.conf

Golang - interface

type iConfig interface {
	ReadConfig() (map[string]string, error)
	WriteConfig() error
}

Bash - getopts

VERSION=0.1.0
declare OPT_D OPT_L OPT_R

getopts_cli() {
	while getopts hvd:l:r: opt; do
		case "$opt" in
			h) show_help $0; exit;;
			v) echo $VERSION; exit;;
			d) OPT_D="$OPTARG";;
			l) OPT_L="$OPTARG";;
			r) OPT_R="$OPTARG";;
			?) exit 1;;
		esac
	done
}

getopts_cli "$@"

Ruby - gets

全局的 gets 在使用时类似 Perl 的钻石运算符。

while gets
  print $_
end

当执行 ruby script.rb,这个程序打印的是输入流的输入。当执行 ruby script.rb /etc/hosts /etc/crontab,它顺次打印这两个文件。🎉️

如果要限定只从标准输入读取一行,可以采用 $stdin.gets

Ruby - 格式化字符串

除了字符串内插(#{variable}),还可以:

formatter = "%{first} %{second} %{third} %{fourth}"

puts formatter % { first: 1, second: 2, third: 3, fourth: 4 }
puts formatter % { first: "one", second: "two", third: "three", fourth: "four" }
Ph'nglui mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn
评论  
留下你的脚步
推荐阅读