osx

package
v0.19.4 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: Apache-2.0 Imports: 25 Imported by: 0

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

View Source
const (
	OSMac     = "darwin"
	OSWindows = "windows"
	OSLinux   = "linux"
)

定义操作系统常量

Variables

View Source
var GetGOOS = func() string {
	return runtime.GOOS
}

GetGOOS 返回当前操作系统

Functions

func BuildObjectURL

func BuildObjectURL(domain, key string) string

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

func CheckImageExists(filename string) error

CheckImageExists 检查图像文件是否存在并且有效

func Command

func Command(bin string, argv []string, baseDir string) ([]byte, error)

Command 执行系统命令

func Copy

func Copy(src, dest string) error

Copy 复制文件从源路径到目标路径

func CreateIfNotExist

func CreateIfNotExist(file string) (*os.File, error)

CreateIfNotExist 如果文件不存在则创建它

func DirHasContent

func DirHasContent(dir string) (bool, []string, error)

DirHasContent 检查目录是否有内容(即是否有非空文件)

func FileExists

func FileExists(file string) bool

FileExists 检查文件是否存在

func FileNameWithoutExt

func FileNameWithoutExt(file string) string

FileNameWithoutExt 返回不带扩展名的文件名

func FindFiles

func FindFiles(pattern string) ([]string, error)

FindFiles 查找匹配 glob 模式的文件,支持 ** 通配符用于递归匹配 参数:pattern - glob 模式,支持标准模式和递归模式(**/) 返回:匹配的文件路径切片和可能的错误 示例:

  • "./pb/*.pb.go" - 查找 pb 目录下所有 pb.go 文件
  • "./pb/**/*.pb.go" - 递归查找所有子目录下的 pb.go 文件

func FindFilesRecursive

func FindFilesRecursive(pattern string) ([]string, error)

FindFilesRecursive 递归查找文件,支持 ** 通配符 内部函数,用于处理包含 ** 的模式

func GetCurrentUsage

func GetCurrentUsage() uint64

GetCurrentUsage 获取当前内存使用量(字节)

func GetDatacenterId

func GetDatacenterId() int64

GetDatacenterId 获取数据中心ID 优先级: 自定义环境变量 > 容器编排平台 > 数据中心标识 > 默认值1 注意:不使用 REGION/ZONE 等区域变量,因为同一区域内的多台机器值相同,无法区分节点 返回范围: 0 到 (maxDatacenterID-1),默认 0-31(雪花算法标准)

func GetDirFiles

func GetDirFiles(dir string) ([]string, error)

GetDirFiles 获取指定目录及其子目录下的所有文件路径 参数:dir - 目录路径 返回:所有文件的路径切片和可能的错误

func GetHostName

func GetHostName() (string, error)

GetHostName 获取主机名,如果失败则返回错误

结果在进程内缓存,只在首次成功时读取一次系统调用

func GetMaxDatacenterID

func GetMaxDatacenterID() int64

GetMaxDatacenterID 获取 DatacenterID 的最大值

func GetMaxSnowflakeWorkerID

func GetMaxSnowflakeWorkerID() int64

GetMaxSnowflakeWorkerID 获取雪花算法 WorkerID 的最大值

func GetMaxWorkerID

func GetMaxWorkerID() int64

GetMaxWorkerID 获取 WorkerID 的最大值

func GetMemoryStats

func GetMemoryStats() runtime.MemStats

GetMemoryStats 获取当前内存统计信息

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 Getenv

func Getenv[T any](key string, defaultValue T) T

Getenv 函数用于获取指定环境变量的值 如果环境变量不存在或无法解析,则返回提供的默认值 T 是一个类型参数,可以是任意类型

func HashUnixMicroCipherText

func HashUnixMicroCipherText() string

HashUnixMicroCipherText 生成基于时间戳和主机名的哈希密文

func IsLinux

func IsLinux() bool

IsLinux 检查当前操作系统是否为 Linux

func IsMac

func IsMac() bool

IsMac 检查当前操作系统是否为 macOS

func IsSupportedOS

func IsSupportedOS() bool

IsSupportedOS 检查当前操作系统是否在支持的操作系统列表中

func IsWindows

func IsWindows() bool

IsWindows 检查当前操作系统是否为 Windows

func JoinPaths

func JoinPaths(absolutePath, relativePath string) string

JoinPaths 连接绝对路径和相对路径。

func JoinURL

func JoinURL(base, p string) (string, error)

JoinURL 拼接URL,确保路径拼接正确

func MkdirIfNotExist

func MkdirIfNotExist(dir string) error

MkdirIfNotExist 如果目录不存在则创建它

func MkdirTemp

func MkdirTemp() string

MkdirTemp 创建一个临时目录,如果创建失败则程序退出

func ParseUrlPath

func ParseUrlPath(urlString string) (path string)

ParseUrlPath 解析Url中Path部分

func RemoveIfExist

func RemoveIfExist(filename string) error

RemoveIfExist 如果文件存在则删除它

func SafeGetHostName

func SafeGetHostName() string

SafeGetHostName 安全获取主机名,失败时返回随机字符串

成功的结果在进程内缓存失败时每次都会新生成随机串,不缓存——否则一次暂时 的失败会把这个随机串固化成进程的身份

func SaveImage

func SaveImage(filename string, imgData []byte, quality int) error

SaveImage 将字节数据保存为指定文件名的图片

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

func StableHashSlot(s string, minNum, maxNum int) int

StableHashSlot 根据输入字符串 s 和范围 [minNum, maxNum],返回一个稳定且范围内的整数 使用加密哈希 sha256,抗碰撞更强 如果 maxNum < minNum,会 panic 如果 maxNum == minNum,直接返回 minNum

func WriteContentToFile

func WriteContentToFile(filePath, content string) error

WriteContentToFile 将内容追加写入指定文件

Types

type GrowthRate

type GrowthRate struct {
	Duration   time.Duration
	Percentage float64
	Absolute   int64
}

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 NewAdvancedMonitor

func NewAdvancedMonitor() *Monitor

NewAdvancedMonitor 创建高级内存监控器

func NewMonitor

func NewMonitor(threshold uint64) *Monitor

NewMonitor 创建内存监控器(简化版,使用单一阈值)

func (*Monitor) AddThreshold

func (m *Monitor) AddThreshold(level ThresholdLevel, value uint64) *Monitor

AddThreshold 添加阈值

func (*Monitor) ClearHistory

func (m *Monitor) ClearHistory()

ClearHistory 清空历史记录

func (*Monitor) EnableGrowthCheck

func (m *Monitor) EnableGrowthCheck(threshold float64, window time.Duration) *Monitor

EnableGrowthCheck 启用增长率检查

func (*Monitor) GetHistory

func (m *Monitor) GetHistory() []Snapshot

GetHistory 获取历史快照

func (*Monitor) GetLastSnapshot

func (m *Monitor) GetLastSnapshot() *Snapshot

GetLastSnapshot 获取最后一次快照

func (*Monitor) GetStats

func (m *Monitor) GetStats() MonitorStats

GetStats 获取监控统计信息

func (*Monitor) OnCheck

func (m *Monitor) OnCheck(fn func(snapshot Snapshot)) *Monitor

OnCheck 设置每次检查时的回调函数(可用于日志记录)

func (*Monitor) OnCritical

func (m *Monitor) OnCritical(fn func(snapshot Snapshot)) *Monitor

OnCritical 设置严重级别回调

func (*Monitor) OnGrowthAlert

func (m *Monitor) OnGrowthAlert(fn func(rate GrowthRate, snapshot Snapshot)) *Monitor

OnGrowthAlert 设置增长率告警回调

func (*Monitor) OnWarning

func (m *Monitor) OnWarning(fn func(snapshot Snapshot)) *Monitor

OnWarning 设置警告级别回调

func (*Monitor) SetCheckOnce

func (m *Monitor) SetCheckOnce(once bool) *Monitor

SetCheckOnce 设置是否只检查一次超标就停止监控

func (*Monitor) SetMaxHistory

func (m *Monitor) SetMaxHistory(max int) *Monitor

SetMaxHistory 设置最大历史记录数

func (*Monitor) SetMetricType

func (m *Monitor) SetMetricType(metricType MetricType) *Monitor

SetMetricType 设置监控指标类型

func (*Monitor) Start

func (m *Monitor) Start(ctx context.Context, interval time.Duration)

Start 启动监控(阻塞)

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) Release

func (c *RunTimeCaller) Release()

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 内存快照

func GetCurrentSnapshot

func GetCurrentSnapshot() Snapshot

GetCurrentSnapshot 获取当前内存快照(不启动监控)

type Threshold

type Threshold struct {
	Level ThresholdLevel
	Value uint64
}

Threshold 阈值配置

type ThresholdLevel

type ThresholdLevel int

ThresholdLevel 阈值级别

const (
	LevelWarning  ThresholdLevel = iota // 警告级别
	LevelCritical                       // 严重级别
)

type WorkerIDConfig

type WorkerIDConfig struct {
	// contains filtered or unexported fields
}

WorkerIDConfig WorkerID 配置

Jump to

Keyboard shortcuts

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