Documentation
¶
Overview ¶
* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-12-04 19:31:22 * @FilePath: \go-toolbox\pkg\osx\base.go * @Description: 操作系统相关工具函数 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-09-21 03:50:15 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-09-21 03:55:26 * @FilePath: \go-toolbox\pkg\osx\env.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-10-28 09:52:21 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-11 10:53:21 * @FilePath: \go-toolbox\pkg\osx\file.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-26 13:32:51 * @FilePath: \go-toolbox\pkg\osx\goos.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-12-30 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-01-24 15:52:18 * @FilePath: \go-toolbox\pkg\osx\monitor.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-09 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-11 17:08:09 * @FilePath: \go-toolbox\pkg\osx\path.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
Index ¶
- Constants
- Variables
- func BuildObjectURL(domain, key string) string
- func CheckImageExists(filename string) error
- func Command(bin string, argv []string, baseDir string) ([]byte, error)
- func Copy(src, dest string) error
- func CreateIfNotExist(file string) (*os.File, error)
- func DirHasContent(dir string) (bool, []string, error)
- func FileExists(file string) bool
- func FileNameWithoutExt(file string) string
- func FindFiles(pattern string) ([]string, error)
- func FindFilesRecursive(pattern string) ([]string, error)
- func GetCurrentUsage() uint64
- func GetDatacenterId() int64
- func GetDirFiles(dir string) ([]string, error)
- func GetHostName() (string, error)
- func GetMaxDatacenterID() int64
- func GetMaxSnowflakeWorkerID() int64
- func GetMaxWorkerID() int64
- func GetMemoryStats() runtime.MemStats
- func GetServerNode() string
- func GetWorkerId() int64
- func GetWorkerIdForSnowflake() int64
- func Getenv[T any](key string, defaultValue T) T
- func HashUnixMicroCipherText() string
- func IsLinux() bool
- func IsMac() bool
- func IsSupportedOS() bool
- func IsWindows() bool
- func JoinPaths(absolutePath, relativePath string) string
- func JoinURL(base, p string) (string, error)
- func MkdirIfNotExist(dir string) error
- func MkdirTemp() string
- func ParseUrlPath(urlString string) (path string)
- func RemoveIfExist(filename string) error
- func SafeGetHostName() string
- func SaveImage(filename string, imgData []byte, quality int) error
- func SetMaxDatacenterID(max int64)
- func SetMaxSnowflakeWorkerID(max int64)
- func SetMaxWorkerID(max int64)
- func StableHashSlot(s string, minNum, maxNum int) int
- func WriteContentToFile(filePath, content string) error
- type GrowthRate
- type MetricType
- type Monitor
- func (m *Monitor) AddThreshold(level ThresholdLevel, value uint64) *Monitor
- func (m *Monitor) ClearHistory()
- func (m *Monitor) EnableGrowthCheck(threshold float64, window time.Duration) *Monitor
- func (m *Monitor) GetHistory() []Snapshot
- func (m *Monitor) GetLastSnapshot() *Snapshot
- func (m *Monitor) GetStats() MonitorStats
- func (m *Monitor) OnCheck(fn func(snapshot Snapshot)) *Monitor
- func (m *Monitor) OnCritical(fn func(snapshot Snapshot)) *Monitor
- func (m *Monitor) OnGrowthAlert(fn func(rate GrowthRate, snapshot Snapshot)) *Monitor
- func (m *Monitor) OnWarning(fn func(snapshot Snapshot)) *Monitor
- func (m *Monitor) SetCheckOnce(once bool) *Monitor
- func (m *Monitor) SetMaxHistory(max int) *Monitor
- func (m *Monitor) SetMetricType(metricType MetricType) *Monitor
- func (m *Monitor) Start(ctx context.Context, interval time.Duration)
- type MonitorStats
- type RunTimeCaller
- type Snapshot
- type Threshold
- type ThresholdLevel
- type WorkerIDConfig
Constants ¶
const ( OSMac = "darwin" OSWindows = "windows" OSLinux = "linux" )
定义操作系统常量
Variables ¶
var GetGOOS = func() string { return runtime.GOOS }
GetGOOS 返回当前操作系统
Functions ¶
func BuildObjectURL ¶
BuildObjectURL 根据存储域名和对象键构造完整访问 URL,统一处理 scheme、斜杠与空值。
行为:
- domain 或 key 为空时返回空字符串,避免拼出 "https:///key" 这类残缺 URL
- domain 已带 http:// 或 https:// 时不再补 scheme,否则默认追加 https://
- domain 末尾与 key 开头的斜杠会被规范化,绝不出现重复斜杠
示例:
BuildObjectURL("cdn.example.com", "icons/app.png") // "https://cdn.example.com/icons/app.png"
BuildObjectURL("https://cdn.example.com/", "/a/b.png") // "https://cdn.example.com/a/b.png"
BuildObjectURL("", "icon.png") // ""
BuildObjectURL("cdn.example.com", "") // ""
func CheckImageExists ¶
CheckImageExists 检查图像文件是否存在并且有效
func CreateIfNotExist ¶
CreateIfNotExist 如果文件不存在则创建它
func DirHasContent ¶
DirHasContent 检查目录是否有内容(即是否有非空文件)
func FileNameWithoutExt ¶
FileNameWithoutExt 返回不带扩展名的文件名
func FindFiles ¶
FindFiles 查找匹配 glob 模式的文件,支持 ** 通配符用于递归匹配 参数:pattern - glob 模式,支持标准模式和递归模式(**/) 返回:匹配的文件路径切片和可能的错误 示例:
- "./pb/*.pb.go" - 查找 pb 目录下所有 pb.go 文件
- "./pb/**/*.pb.go" - 递归查找所有子目录下的 pb.go 文件
func FindFilesRecursive ¶
FindFilesRecursive 递归查找文件,支持 ** 通配符 内部函数,用于处理包含 ** 的模式
func GetDatacenterId ¶
func GetDatacenterId() int64
GetDatacenterId 获取数据中心ID 优先级: 自定义环境变量 > 容器编排平台 > 数据中心标识 > 默认值1 注意:不使用 REGION/ZONE 等区域变量,因为同一区域内的多台机器值相同,无法区分节点 返回范围: 0 到 (maxDatacenterID-1),默认 0-31(雪花算法标准)
func GetDirFiles ¶
GetDirFiles 获取指定目录及其子目录下的所有文件路径 参数:dir - 目录路径 返回:所有文件的路径切片和可能的错误
func GetMaxSnowflakeWorkerID ¶
func GetMaxSnowflakeWorkerID() int64
GetMaxSnowflakeWorkerID 获取雪花算法 WorkerID 的最大值
func GetServerNode ¶
func GetServerNode() string
GetServerNode 获取当前服务节点标识(K8s 环境下为 Pod 名称) 用于 HTTP 响应头 X-Server-Node 和 gRPC metadata x-server-node 透传, 便于在分布式环境下定位处理请求的具体节点
优先级: POD_NAME 环境变量 > HOSTNAME 环境变量 > os.Hostname() > 随机生成的标识
与 GetWorkerId 的区别:
- GetWorkerId 返回数字 ID(提取序号或哈希取模),用于雪花算法
- GetServerNode 返回原始节点名称(保留 Pod 名称原文),用于链路追踪和流量定位
func GetWorkerId ¶
func GetWorkerId() int64
GetWorkerId 获取唯一的 Worker ID (智能增强版) 优先级: K8s Pod Name > K8s Hostname > 环境变量 > 主机名哈希 支持环境变量: POD_NAME, HOSTNAME, WORKER_ID, NODE_ID, POD_ORDINAL 返回范围: 0 到 (maxWorkerID-1),默认 0-1023
func GetWorkerIdForSnowflake ¶
func GetWorkerIdForSnowflake() int64
GetWorkerIdForSnowflake 获取适合雪花算法的 WorkerID(0-31,5位)
func HashUnixMicroCipherText ¶
func HashUnixMicroCipherText() string
HashUnixMicroCipherText 生成基于时间戳和主机名的哈希密文
func SafeGetHostName ¶
func SafeGetHostName() string
SafeGetHostName 安全获取主机名,失败时返回随机字符串
成功的结果在进程内缓存失败时每次都会新生成随机串,不缓存——否则一次暂时 的失败会把这个随机串固化成进程的身份
func SetMaxDatacenterID ¶
func SetMaxDatacenterID(max int64)
SetMaxDatacenterID 设置 DatacenterID 的最大值(范围限制) 默认值: 32(雪花算法标准)
func SetMaxSnowflakeWorkerID ¶
func SetMaxSnowflakeWorkerID(max int64)
SetMaxSnowflakeWorkerID 设置雪花算法 WorkerID 的最大值(范围限制) 默认值: 32(雪花算法标准的5位)
func SetMaxWorkerID ¶
func SetMaxWorkerID(max int64)
SetMaxWorkerID 设置 WorkerID 的最大值(范围限制) 默认值: 1024
func StableHashSlot ¶
StableHashSlot 根据输入字符串 s 和范围 [minNum, maxNum],返回一个稳定且范围内的整数 使用加密哈希 sha256,抗碰撞更强 如果 maxNum < minNum,会 panic 如果 maxNum == minNum,直接返回 minNum
func WriteContentToFile ¶
WriteContentToFile 将内容追加写入指定文件
Types ¶
type GrowthRate ¶
GrowthRate 增长率统计
type MetricType ¶
type MetricType int
MetricType 监控指标类型
const ( MetricAlloc MetricType = iota // 已分配内存 MetricTotalAlloc // 累计分配内存 MetricSys // 系统内存 MetricHeapAlloc // 堆内存分配 MetricHeapInuse // 堆内存使用 MetricStackInuse // 栈内存使用 MetricGoroutines // Goroutine数量 )
type Monitor ¶
type Monitor struct {
// contains filtered or unexported fields
}
Monitor 内存监控器
func (*Monitor) AddThreshold ¶
func (m *Monitor) AddThreshold(level ThresholdLevel, value uint64) *Monitor
AddThreshold 添加阈值
func (*Monitor) EnableGrowthCheck ¶
EnableGrowthCheck 启用增长率检查
func (*Monitor) GetLastSnapshot ¶
GetLastSnapshot 获取最后一次快照
func (*Monitor) OnCritical ¶
OnCritical 设置严重级别回调
func (*Monitor) OnGrowthAlert ¶
func (m *Monitor) OnGrowthAlert(fn func(rate GrowthRate, snapshot Snapshot)) *Monitor
OnGrowthAlert 设置增长率告警回调
func (*Monitor) SetCheckOnce ¶
SetCheckOnce 设置是否只检查一次超标就停止监控
func (*Monitor) SetMaxHistory ¶
SetMaxHistory 设置最大历史记录数
func (*Monitor) SetMetricType ¶
func (m *Monitor) SetMetricType(metricType MetricType) *Monitor
SetMetricType 设置监控指标类型
type MonitorStats ¶
type MonitorStats struct {
CheckCount uint64 `json:"check_count"`
ExceedCount uint64 `json:"exceed_count"`
LastCheckTime time.Time `json:"last_check_time"`
HistoryCount int `json:"history_count"`
}
MonitorStats 监控统计信息
type RunTimeCaller ¶
type RunTimeCaller struct {
Pc uintptr // 程序计数器
File string // 文件路径
Line int // 行号
FuncName string // 函数名
}
RunTimeCaller 运行时调用栈信息
func GetRuntimeCaller ¶
func GetRuntimeCaller(skip int) *RunTimeCaller
GetRuntimeCaller 获取调用栈信息,调用者使用完需调用 Release() 归还对象
func (*RunTimeCaller) String ¶
func (c *RunTimeCaller) String() string
String 返回调用栈的格式化字符串,包含函数名、文件名和行号
type Snapshot ¶
type Snapshot struct {
Timestamp time.Time
Alloc uint64
TotalAlloc uint64
Sys uint64
HeapAlloc uint64
HeapInuse uint64
StackInuse uint64
Goroutines int
NumGC uint32
GCCPUFrac float64
}
Snapshot 内存快照
type ThresholdLevel ¶
type ThresholdLevel int
ThresholdLevel 阈值级别
const ( LevelWarning ThresholdLevel = iota // 警告级别 LevelCritical // 严重级别 )
type WorkerIDConfig ¶
type WorkerIDConfig struct {
// contains filtered or unexported fields
}
WorkerIDConfig WorkerID 配置