Redact 脱敏文本中的PII信息
(text string)
| 39 | |
| 40 | // Redact 脱敏文本中的PII信息 |
| 41 | func (r *PIIRedactor) Redact(text string) string { |
| 42 | if r.detector == nil || text == "" { |
| 43 | return text |
| 44 | } |
| 45 | |
| 46 | ctx := context.Background() |
| 47 | matches, err := r.detector.Detect(ctx, text) |
| 48 | if err != nil || len(matches) == 0 { |
| 49 | return text |
| 50 | } |
| 51 | |
| 52 | // 按位置倒序排列,从后往前替换,避免位置偏移 |
| 53 | for i := len(matches) - 1; i >= 0; i-- { |
| 54 | match := matches[i] |
| 55 | replacement := r.replacer[match.Type] |
| 56 | if replacement == "" { |
| 57 | replacement = "[PII]" |
| 58 | } |
| 59 | |
| 60 | text = text[:match.Start] + replacement + text[match.End:] |
| 61 | } |
| 62 | |
| 63 | return text |
| 64 | } |
| 65 | |
| 66 | // SetReplacement 设置特定PII类型的替换文本 |
| 67 | func (r *PIIRedactor) SetReplacement(piiType PIIType, replacement string) { |
no test coverage detected