misc

package module
v0.0.0-...-ae06c18 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2025 License: MIT Imports: 15 Imported by: 0

README

misc

CI

通用实用库,提供常用的工具函数与类型,覆盖摘要/密码、函数式封装、MIME 解析、模板插值、堆栈信息、零拷贝转换与零值判断等能力。

  • 模块路径:go-slim.dev/misc
  • Go 版本:1.24

功能概览

  • 摘要/密码:MD5Sha1Sha256PasswordHash/PasswordVerify
  • 函数组合:Call/CallWithWrap/WrapWithMustCall/MustCallWith
  • MIME 解析:ExtensionByTypeTypeByExtensionCharsetByType
  • 模板插值:Strtr/TmplInterpolateTagFunc
  • 堆栈信息:Stack()(包含源码行)
  • 零拷贝转换:UnsafeBytesToStringUnsafeStringToBytes(需谨慎使用)
  • 零值判断:IsZero(支持指针递归判断)

安装

go get go-slim.dev/misc

快速示例

摘要与密码
package main

import (
    "fmt"
    "go-slim.dev/misc"
)

func main() {
    fmt.Println(misc.MD5("hello"))
    fmt.Println(misc.Sha1("hello"))
    fmt.Println(misc.Sha256("hello"))

    hash := misc.PasswordHash("S3cret!")
    ok := misc.PasswordVerify("S3cret!", hash)
    fmt.Println("password ok:", ok)
}
函数组合/封装
v, err := misc.Call(func() (int, error) { return 42, nil })
_ = misc.MustCall(func() (string, error) { return "ok", nil })

wrapped := misc.Wrap(func(a int) int { return a * 2 })
result := wrapped(21) // 42
_ = result
MIME 解析
ext := misc.ExtensionByType("application/json; charset=utf-8") // .json
typ := misc.TypeByExtension(".png")                            // image/png
cs  := misc.CharsetByType("text/html; charset=utf-8")          // utf-8
_ = []string{ext, typ, cs}
模板插值
s := misc.Strtr("Hello, {name}!", map[string]string{"{name}": "Alice"})

out, _ := misc.Tmpl("/user/{{.ID}}?q={{.Q}}", map[string]any{"ID": 7, "Q": "k"})

// 高级:自定义标签函数
upper := misc.TagFunc("upper", func(s string) string { return strings.ToUpper(s) })
res, _ := misc.Interpolate("Hi, {{upper .Name}}", map[string]any{"Name": "bob"}, upper)
_ = []string{s, out, res}
堆栈追踪
trace := misc.Stack(0) // 跳过 0 层,包含函数、文件与行号
fmt.Println(trace)
零拷贝转换(危险)
// 注意:仅在明确理解风险时使用!
b := []byte("hello")
s := misc.UnsafeBytesToString(b)
bs := misc.UnsafeStringToBytes(s)
_ = []any{s, bs}
零值判断
type T struct{ N int }
var p *T
_ = misc.IsZero(0)   // true
_ = misc.IsZero("")  // true
_ = misc.IsZero(p)   // true(nil 指针)
_ = misc.IsZero(T{}) // true

运行测试

go test ./...

许可证

本项目使用 MIT License,详见 LICENSE

Documentation

Overview

Package misc 提供通用的实用工具函数与类型:

  • 摘要/密码:MD5、Sha1、Sha256、PasswordHash/Verify
  • 函数组合:Call/CallWith、Wrap/WrapWith、MustCall/MustCallWith
  • MIME 解析:ExtensionByType、TypeByExtension、CharsetByType
  • 模板插值:Strtr/Tmpl、Interpolate、TagFunc
  • 堆栈信息:Stack(包含源码行)
  • 零拷贝转换:UnsafeBytesToString、UnsafeStringToBytes 等(需谨慎使用)
  • 零值判断:IsZero(支持指针递归判断)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BytesToString

func BytesToString(b []byte) string

BytesToString 使用 Go 1.20+ 的 unsafe 辅助 API 将字节切片零拷贝转换为字符串。 注意:结果与原切片共享底层数据,需保证原切片后续不被修改。

func Call

func Call(fns ...func() error) error

Call 依次调用提供的函数,若任一函数返回错误,则立即返回该错误。

func CallWith

func CallWith[T any](val T, fns ...func(T) error) error

CallWith 依次调用提供的函数并传入相同参数,若任一函数返回错误,则立即返回该错误。

func CharsetByType

func CharsetByType(typ string) string

CharsetByType 针对 text/* 类型返回 "charset=utf-8",否则返回空字符串。

func ExtensionByType

func ExtensionByType(mimeType string) string

ExtensionByType 根据 MIME 类型返回一个匹配的扩展名(包含点,如 .png)。 优先使用内置表,其次回退到标准库 mime.ExtensionsByType。 若无法识别,返回空字符串。

func Interpolate

func Interpolate(template, startTag, endTag string, w io.Writer, f TagFunc) (int64, error)

Interpolate calls f on each template tag (placeholder) occurrence.

Returns the number of bytes written to w.

func IsZero

func IsZero[T any](v T) bool

IsZero 泛型零值判断 https://stackoverflow.com/questions/74000242/in-golang-how-to-compare-interface-as-generics-type-to-nil IsZero 判断任意泛型值是否为零值。 若为指针类型,会递归地解引用直至基础值再判断。

func MD5

func MD5(str string) string

MD5 计算字符串的 MD5 摘要,并以大写十六进制字符串返回。

func MustCall

func MustCall(fns ...func() error)

MustCall 依次调用函数;若出现错误,打印函数名并以 fatal 退出程序。

func MustCallWith

func MustCallWith[T any](val T, fns ...func(T) error)

MustCallWith 依次调用函数并传入相同参数;若出现错误,打印函数名并以 fatal 退出程序。

func PasswordHash

func PasswordHash(password string) (string, error)

PasswordHash 使用 bcrypt 生成口令哈希。 返回的哈希可用于后续的 PasswordVerify 校验。

func PasswordVerify

func PasswordVerify(password, hash string) bool

PasswordVerify 使用 bcrypt 对明文口令与哈希进行校验。 返回 true 表示匹配,false 表示不匹配。

func Sha1

func Sha1(str string) string

Sha1 计算字符串的 SHA-1 摘要,并以十六进制字符串返回(小写)。

func Sha256

func Sha256(str string) string

Sha256 计算字符串的 SHA-256 摘要,并以十六进制字符串返回(小写)。

func SliceByteToString

func SliceByteToString(b []byte) string

SliceByteToString convert a byte slice to string Deprecated: use UnsafeBytesToString func SliceByteToString 将字节切片转换为字符串(零拷贝)。 注意:属于不安全转换,底层数据共享;若切片内容随后被修改,将影响字符串视图。

func Stack

func Stack(skip int) string

Stack will skip back the provided number of frames and return a stack trace with source code. Although we could just use debug.Stack(), this routine will return the source code and skip back the provided number of frames - i.e. allowing us to ignore preceding function calls. A skip of 0 returns the stack trace for the calling function, not including this call. If the problem is a lack of memory of course all this is not going to work... Stack 返回带源码行的堆栈信息。参数 skip 用于跳过前置帧(0 表示调用者)。 与 debug.Stack 不同之处在于:本函数尝试同时输出对应源码行,方便定位。

func StringToBytes

func StringToBytes(s string) []byte

StringToBytes 使用 Go 1.20+ 的 unsafe 辅助 API 将字符串零拷贝转换为字节切片。 注意:得到的切片只读,切勿修改其内容。

func StringToSliceByte

func StringToSliceByte(s string) []byte

StringToSliceByte convert a string to byte slice. Deprecated: use UnsafeStringToBytes func StringToSliceByte 将字符串转换为字节切片(零拷贝)。 注意:属于不安全转换,返回切片不可修改(否则会触发未定义行为)。

func Strtr

func Strtr(template string, data map[string]any) (string, error)

Strtr translate characters or replace substrings

func Tmpl

func Tmpl(template, startTag, endTag string, data map[string]any) (string, error)

func TypeByExtension

func TypeByExtension(ext string) string

TypeByExtension 根据扩展名(可不含点)返回对应的 MIME 类型。 优先匹配内置表,不存在时回退到标准库 mime.TypeByExtension。

func UnsafeBytesToString

func UnsafeBytesToString(b []byte) string

UnsafeBytesToString uses Go's unsafe package to convert a byte slice to a string. Deprecated: use BytesToString instead. UnsafeBytesToString 使用 Go 1.20+ 的 unsafe 辅助 API 进行零拷贝转换。 注意:结果与原切片共享底层数据,需保证原切片后续不被修改。

func UnsafeStringToBytes

func UnsafeStringToBytes(s string) []byte

UnsafeStringToBytes uses Go's unsafe package to convert a string to a byte slice. Deprecated: use StringToBytes instead. UnsafeStringToBytes 使用 Go 1.20+ 的 unsafe 辅助 API 将字符串零拷贝转换为字节切片。 注意:得到的切片只读,切勿修改其内容。

func Wrap

func Wrap(fns ...func() error) func() error

Wrap 将一组无参函数组合为一个函数,调用时按顺序执行,遇到错误即返回。

func WrapWith

func WrapWith[T any](fns ...func(T) error) func(val T) error

WrapWith 将一组接收相同参数的函数组合为一个函数,调用时按顺序执行,遇到错误即返回。

Types

type TagFunc

type TagFunc func(w io.Writer, tag string) (int, error)

TagFunc can be used as a substitution value in the map passed to Interpolate. Interpolate functions pass tag (placeholder) name in 'tag' argument.

TagFunc must be safe to call from concurrently running goroutines.

TagFunc must write contents to w and return the number of bytes written.

Jump to

Keyboard shortcuts

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