我正在执行一些输出敏感数据的exec.Command
。我想过滤掉这些数据。由于您可以将 stdout
writer 设置为 Command
结构,我的想法是编写一个自定义的 io.Writer
,它基本上消耗输出和过滤器给定单词的输出。
type passwordFilter struct {
keyWord string
}
func (pf passwordFilter) Write(p []byte) (n int, err error) {
// this is where I have no idea what to do
// I think I should somehow use a scanner and then filter
// out = strings.Replace(out, pf.keyWord, "*******", -1)
// something like this
// but I have to deal with byte array here
}
func main() {
pf := passwordFilter{keyWord: "password123"}
cmd := exec.Command(someBinaryFile)
cmd.Stdout = pf
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
}
我不确定我的方向是否正确,但我确信我可以以某种方式重用此处现有的 io.Writers 或扫描仪。
最佳答案
使用Cmd.StdoutPipe让读者了解程序的输出。在该阅读器上使用扫描仪。
cmd := exec.Command(someBinaryFile)
r, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
s := bufio.NewScanner(r)
for s.Scan() {
out := s.String()
out = strings.Replace(out, pf.keyWord, "*******", -1)
// write out to destination
}
if s.Err() != nil {
log.Fatal(s.Err())
}
if err := cmd.Wait(); err != nil {
log.Fatal(err)
}
关于go - 通过 Go 中的自定义 io.Writer 编辑敏感数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49967523/