strutil

package
v1.4.53 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 2, 2026 License: MIT Imports: 3 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

strutil

strutil 是一个高性能、高可靠性的企业级 Go 语言字符串处理工具箱,隶属于 gotools 基础组件库。

🚀 核心功能:安全文件名净化 (Sanitization)

在文件上传、导出或分发场景中,不可信的用户输入或复杂的业务拼接(如中英文括号、空格、系统保留字)极易引发物理存储失败、路径穿越漏洞(Path Traversal)或终端显示乱码。

ParseSafeFileName 函数采用严格白名单物理清洗机制,确保输出的文件名在 Windows、Linux、macOS 等主流操作系统中均能安全合规地落盘。

✨ 特性
  • 前置符号映射:智能将括号 ()、斜杠 /\、冒号 :、问号 ? 等业务常见分隔符规整为统一的单下划线 _。
  • 严格白名单过滤:基于 rune 级高效遍历,仅保留英文字母、数字、中划线 -、标准下划线 _ 以及基本汉字区间(CJK)。
  • 格式美化:自动合并连续的下划线(如 ___ -> _),并裁剪首尾的残余中/下划线。
  • 异常熔断拦截:若输入全为空格或非法字符导致最终文件名为空,函数将直接熔断并返回安全错误,拒绝生成无意义隐患文件。
  • 并发安全与高性能:核心正则经包级全局预编译,无运行时重复编译开销,完美抗住高并发。

🛠 快速上手

1. 基础调用
package main

import (
	"fmt"
	"log"

	"your_project/utils/strutil"
)

func main() {
	rawInput := " 1779765732_测试品牌(gcj)/测试卡券??__2元 "
	
	safeName, err := strutil.ParseSafeFileName(rawInput)
	if err != nil {
		log.Fatalf("文件名不合法: %v", err)
	}

	fmt.Println(safeName)
	// Output: 1779765732_测试品牌_gcj_测试卡券_2元
}

Documentation

Overview

Package strutil 提供字符串处理工具函数。 包括文件名安全处理、字符串格式化等实用功能。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ParseSafeFileName

func ParseSafeFileName(rawName string) (string, error)

ParseSafeFileName 终极清洗文件名,彻底剔除中英文空格、控制字符、中英文斜杠、括号及特殊符号。 如果清洗后文件名为空,则返回错误。 参数:

  • rawName: 原始拼接的文件名字符串

返回:

  • string: 清洗干净后的安全文件名
  • error: 当名字被完全滤空时返回异常

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL