Skip to content

系统与并发标准库:sync、atomic、log、big、container、flag、crypto

这篇覆盖「非文本类」标准库:并发原语、日志、大数、容器、命令行、密码学。每个包给出高频 API 和实战坑。

一、sync 包:锁和同步

1.1 Mutex 与 RWMutex

go
type Counter struct {
	mu sync.Mutex
	n  int
}

func (c *Counter) Inc() {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.n++
}

func (c *Counter) Value() int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.n
}

RWMutex 适合读多写少:

go
type Cache struct {
	mu   sync.RWMutex
	data map[string]string
}

func (c *Cache) Get(key string) (string, bool) {
	c.mu.RLock() // 读锁:多个读者并行
	defer c.mu.RUnlock()
	v, ok := c.data[key]
	return v, ok
}

func (c *Cache) Set(key, value string) {
	c.mu.Lock() // 写锁:独占
	defer c.mu.Unlock()
	c.data[key] = value
}

RWMutex 的坑:

go
// 坑一:写锁饥饿——Go 的 RWMutex 写锁优先(1.21 改进过),
// 高并发读会让写请求排队,别在写关键路径用 RWMutex

// 坑二:不可重入——同一 goroutine 二次 Lock 死锁
// func (c *Cache) GetOrSet(k string) {
//     c.mu.RLock()
//     defer c.mu.RUnlock()
//     if _, ok := c.data[k]; !ok {
//         c.Set(k, "v") // Set 里又要 Lock,死锁!
//     }
// }

// 坑三:拷贝锁——锁是值,复制它就复制了状态
c := Cache{}
c2 := c        // 拷贝了 mutex!go vet 的 copylocks 会报
// 永远传 *Cache

// 坑四:忘记 Unlock(panic 时)——defer 是唯一答案

1.2 WaitGroup:等一组 goroutine

go
var wg sync.WaitGroup

urls := []string{"http://a", "http://b", "http://c"}
for _, url := range urls {
	wg.Add(1) // 必须在 go 之前 Add
	go func(url string) {
		defer wg.Done() // 保证退出时减一
		resp, err := http.Get(url)
		if err != nil {
			return
		}
		resp.Body.Close()
	}(url)
}

wg.Wait() // 阻塞到计数归零

WaitGroup 三条军规:

  1. Add 在 go 语句之前调用(防止 Wait 先跑完)。
  2. Add 的计数用变量而非字面量 1 时,小心 race。
  3. Go 1.25 前 wg.Add(positive) 不能和 Wait 并发——计数器归零后不能再 Add。
go
// 错误:Add 在 goroutine 里,Wait 可能先看到 0
for i := 0; i < 3; i++ {
	go func() {
		wg.Add(1) // 可能 Wait 已经返回
		defer wg.Done()
	}()
}
wg.Wait() // 直接返回,goroutine 还在跑

1.3 Once:一次性初始化

go
var (
	once sync.Once
	db   *sql.DB
)

func getDB() *sql.DB {
	once.Do(func() {
		var err error
		db, err = sql.Open("postgres", dsn)
		if err != nil {
			panic(err) // Once 里 panic,下次调用会重试(Once 不记录失败的初始化)
		}
	})
	return db
}

// Once 的进阶:即使 panic 也记住「执行过」用 once.Do + defer 标记
// 标准 Once:panic 后下次进入会再次执行 f

1.4 Pool:对象复用

go
var bufPool = sync.Pool{
	New: func() any { return new(bytes.Buffer) },
}

func handler(w http.ResponseWriter, r *http.Request) {
	buf := bufPool.Get().(*bytes.Buffer)
	defer func() {
		buf.Reset()          // 必须 Reset,否则残留上次数据
		bufPool.Put(buf)     // 归还
	}()

	buf.WriteString("response")
	w.Write(buf.Bytes())
}

Pool 的语义:GC 会清空 Pool(每个 GC 周期),所以只用来省分配,不保证对象存活。适合「短命、高频、创建成本高」的对象:bytes.Buffer、临时 slice、解码器。别把连接池交给 sync.Pool(连接要保活,用 channel 或专用池)。

1.5 Cond:条件变量

go
// 场景:生产者-消费者,channel 之外的另一种选择
type Queue struct {
	mu    sync.Mutex
	cond  *sync.Cond
	items []int
}

func NewQueue() *Queue {
	q := &Queue{}
	q.cond = sync.NewCond(&q.mu)
	return q
}

func (q *Queue) Push(v int) {
	q.mu.Lock()
	defer q.mu.Unlock()
	q.items = append(q.items, v)
	q.cond.Signal() // 唤醒一个等待者
}

func (q *Queue) Pop() int {
	q.mu.Lock()
	defer q.mu.Unlock()
	for len(q.items) == 0 { // 循环检查,防虚假唤醒
		q.cond.Wait() // 解锁 + 睡眠 + 被唤醒后重新加锁
	}
	v := q.items[0]
	q.items = q.items[1:]
	return v
}

Cond 的三个规则:Wait 必须在持锁状态调用;for 循环检查条件(不用 if);Signal/Broadcast 可以在不加锁时调用。Go 官方建议优先 channel,Cond 只在「多个等待者、复杂条件」时用。

1.6 sync.Map

go
var m sync.Map

// 写
m.Store("key", "value")
m.Delete("key")
m.LoadOrStore("key", "new") // 存在则返回旧的,否则存入
m.LoadAndDelete("key")      // Go 1.15+:取出并删

// 读
v, ok := m.Load("key")

// 遍历(无序)
m.Range(func(k, value any) bool {
	fmt.Println(k, value)
	return true // 返回 false 提前结束
})

适用场景(官方原文精神):键集合相对稳定 + 读远多于写(如配置缓存)。键频繁增长时退化成「一把大锁」,不如自己分片。详见 map 篇。

二、atomic:原子操作

2.1 函数式 API

go
var counter int64

// 加减
atomic.AddInt64(&counter, 1)
atomic.AddInt64(&counter, -1)

// 读取
v := atomic.LoadInt64(&counter)
atomic.StoreInt64(&counter, 100)

// CAS:比较并交换(无锁算法的基石)
swapped := atomic.CompareAndSwapInt64(&counter, 100, 200)

// 交换
old := atomic.SwapInt64(&counter, 300)

// 指针类型
var p unsafe.Pointer
atomic.LoadPointer(&p)
atomic.StorePointer(&p, unsafe.Pointer(&x))

// 万能 Value:装任何类型,同类型才能 Store(混类型 panic)
var config atomic.Value
config.Store(Config{Timeout: 5})
cfg := config.Load().(Config)

2.2 泛型原子类型(Go 1.19+,推荐)

go
// 新 API:类型安全,无需 &,不会传错类型
var counter atomic.Int64
counter.Add(1)
counter.Load()
counter.Store(100)
counter.Swap(200)
counter.CompareAndSwap(200, 300)

var flag atomic.Bool
flag.Store(true)
flag.Load()

var ptr atomic.Pointer[User]
ptr.Store(&User{Name: "alice"})
u := ptr.Load()

// 类型齐全:atomic.Int32/Int64/Uint32/Uint64/Bool/Pointer[T]
// 嵌入结构体零值可用(不像 Mutex 那样需要注意拷贝)
type Stats struct {
	Requests atomic.Int64 // 零值直接可用
	Errors   atomic.Int64
}

atomic vs Mutex 的选择:

场景选择
单个计数器、标志位atomic
「读-改-写」复合逻辑atomic + CAS 循环,或 Mutex
保护多个字段的一致性Mutex
临界区有复杂逻辑Mutex

atomic 不提供 happens-before 之外的同步语义——它保证单个操作原子,不保证两个操作的顺序可见性。多字段协作还是用锁。

go
// CAS 循环:无锁自增的「大版本」
for {
	old := counter.Load()
	if counter.CompareAndSwap(old, old+1) {
		break
	}
	// 竞争失败,重试
}
// 实际写代码:counter.Add(1) 就行,这个循环只是展示原理

2.3 内存序的正确心态

Go 的 atomic 提供 sequentially consistent(顺序一致)语义:所有 goroutine 看到所有 atomic 操作的同一全局顺序。你不需要理解 x86 的 memory barrier——「atomic 操作构成同步点」就是全部心智模型:

go
// 经典模式:用 atomic.Bool 发布「数据已就绪」信号
var ready atomic.Bool
var data []int

func producer() {
	data = make([]int, 100) // 先写数据
	ready.Store(true)       // 再发布信号(Store 之前的写入对所有看到 ready=true 的 goroutine 可见)
}

func consumer() {
	for !ready.Load() { // 看到 true 时,data 的写入一定可见
		runtime.Gosched()
	}
	use(data) // 安全读 data
}

三、log 与 slog

3.1 log 标准库

go
import "log"

// 默认输出到 stderr,带时间戳
log.Println("hello")  // 2024/03/15 10:30:00 hello
log.Printf("id=%d", 1)
log.Fatal("fatal!")   // 打印后 os.Exit(1)——慎用!
log.Panic("panic!")   // 打印后 panic

// 自定义 logger
logger := log.New(os.Stdout, "[myapp] ", log.LstdFlags|log.Lshortfile)
logger.Println("with prefix and file:line")

// flag 组合
log.LstdFlags    // 日期 + 时间
log.Lshortfile   // 文件:行号(有开销,生产少用)
log.Llongfile    // 全路径
log.LUTC         // UTC 时间
log.Lmsgprefix   // 前缀放消息前(Go 1.14+)
log.SetFlags(log.LstdFlags | log.Lmicroseconds)

// 重定向输出
var buf bytes.Buffer
log.SetOutput(&buf)     // 测试时捕获日志
log.SetOutput(io.MultiWriter(os.Stderr, logFile))

// 致命错误的标准处理(库代码别用 Fatal,见错误处理篇)
if err != nil {
	log.Fatalf("init failed: %v", err)
}

3.2 slog:结构化日志(Go 1.21+)

go
import "log/slog"

// 1.21 起官方结构化日志,替代 log 的格式化字符串
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
	Level: slog.LevelInfo,
}))

logger.Info("user login",
	slog.String("user", "alice"),
	slog.Int("attempts", 3),
	slog.Duration("took", 12*time.Millisecond),
)
// {"time":"...","level":"INFO","msg":"user login","user":"alice","attempts":3,"took":"12ms"}

// 快速默认 logger
slog.Info("starting", "port", 8080)
slog.Error("db down", slog.Any("err", err))

// 带字段的上下文 logger(避免每次传字段)
reqLogger := logger.With(slog.String("req_id", "abc123"))
reqLogger.Info("handling") // 自动带 req_id

// 文本格式(开发环境)
slog.New(slog.NewTextHandler(os.Stdout, nil))

// 自定义 level、按 level 分流
level := new(slog.LevelVar)
level.Set(slog.LevelWarn)
logger = slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{LevelVar: level}))

// 适配 io.Writer
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stderr, nil)))

slog 的设计:Logger + Handler(JSON/Text)+ Attr(键值对)。性能是 log + fmt 的 2~3 倍(结构化字段免解析),且原生支持 context 提取(配合 slog.NewContextLogger 模式)。

老项目用 logrus/zap/zerolog 的不用急着重写——新项目直接 slog。

3.3 日志实践军规

go
// 1. 级别语义:Debug 排查、Info 关键流程、Warn 降级可恢复、Error 需人工介入
// 2. 高频路径(每请求多条 Info)考虑采样,否则日志量爆炸
// 3. 敏感信息(密码、token、身份证)脱敏后再记
logger.Info("login", slog.String("phone", maskPhone(user.Phone)))

// 4. 错误必须带 error 字段,不要只打消息
// 坏:log.Printf("query failed: %v", err)  // 丢了堆栈和错误链
// 好:logger.Error("query failed", slog.Any("err", err))

// 5. 不要在日志里打整个大结构体(序列化开销 + 刷屏)
// 6. panic 恢复处打完整堆栈:slog.Error("recovered", slog.String("stack", string(debug.Stack())))

四、math/big:精密计算

go
import "math/big"

// 大整数
a := big.NewInt(1)
for i := int64(2); i <= 50; i++ {
	a.Mul(a, big.NewInt(i)) // 50! = 30414093201713378043612608166064768844377641568960512000000000000
}
fmt.Println(a.String())

// 从字符串构造(处理超长输入)
n, ok := new(big.Int).SetString("123456789012345678901234567890", 10)
fmt.Println(ok, n)

// 运算:Add/Sub/Mul/Div/Mod/Exp/And/Or/Xor/Lsh/Rsh
sum := new(big.Int).Add(a, big.NewInt(1))
diff := new(big.Int).Sub(a, big.NewInt(1))
quo, rem := new(big.Int).QuoRem(a, big.NewInt(7), new(big.Int))

// 大浮点(指定精度)
f := new(big.Float).SetPrec(128).SetFloat64(3.14159265358979)
f.Mul(f, big.NewFloat(2))

// 有理数(分数运算,零误差)
r := new(big.Rat).SetFrac(big.NewInt(1), big.NewInt(3)) // 1/3
r2 := new(big.Rat).SetFrac(big.NewInt(1), big.NewInt(6))
sum := new(big.Rat).Add(r, r2) // 1/2
fmt.Println(sum.FloatString(4)) // "0.5000"

// 应用场景:金额(用 big.Rat 或「分」为单位的 int64)、密码学(RSA/ECC)、科学计算

金额计算的正确姿势:优先「分」为单位的 int64(快、无精度问题);需要小数运算(利率、汇率换算)用 big.Rat;永远不用 float64 存钱(0.1 + 0.2 != 0.3)。

五、container 包

5.1 container/list:双链表

go
import "container/list"

l := list.New()
l.PushBack("a")       // 尾部
l.PushFront("z")      // 头部
l.PushBack("b")       // z a b

e := l.Front()
for ; e != nil; e = e.Next() {
	fmt.Println(e.Value) // z a b
}

// 已知元素操作 O(1)
l.InsertBefore("mid", e) // 在 z 前插入
l.Remove(e)
l.MoveToFront(e)

fmt.Println(l.Len())    // 元素个数
l.Init()                // 清空复用

// 遍历中删除的安全姿势
for e := l.Front(); e != nil; {
	next := e.Next()
	if e.Value == "a" {
		l.Remove(e)
	}
	e = next
}

list 的现代替代:container/list 存在感越来越低——大多数「链表场景」用 slice 更好(缓存友好、无指针追逐)。list 的价值:O(1) 的中间插入删除 + LRU 缓存(配合 map)。

go
// LRU 的标准实现骨架
type LRU struct {
	ll       *list.List               // 双向链表存 key
	cache    map[string]*list.Element // key → 链表节点
	capacity int
}

func (l *LRU) Get(key string) any {
	if e, ok := l.cache[key]; ok {
		l.ll.MoveToFront(e) // 访问后移到头部
		return e.Value
	}
	return nil
}

func (l *LRU) Put(key string, value any) {
	if e, ok := l.cache[key]; ok {
		l.ll.MoveToFront(e)
		e.Value = value
		return
	}
	e := l.ll.PushFront(key)
	l.cache[key] = e
	if l.ll.Len() > l.capacity {
		oldest := l.ll.Back() // 淘汰尾部
		l.ll.Remove(oldest)
		delete(l.cache, oldest.Value.(string))
	}
}

5.2 container/heap:优先队列

go
import "container/heap"

// heap.Interface 五个方法
type IntHeap []int

func (h IntHeap) Len() int            { return len(h) }
func (h IntHeap) Less(i, j int) bool  { return h[i] < h[j] } // 小顶堆
func (h IntHeap) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x any)         { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() any {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[:n-1]
	return x
}

// 使用
h := &IntHeap{2, 1, 5, 3}
heap.Init(h)            // O(n) 建堆
heap.Push(h, 4)         // O(log n) 插入
heap.Pop(h)             // 弹出最小:1
heap.Fix(h, 0)          // 修改元素后恢复堆性质
heap.Remove(h, 2)       // 删指定下标

// 实战:Top-K 问题(求最大的 K 个 = 小顶堆维护 K 个元素)
func topK(nums []int, k int) []int {
	h := &IntHeap{}
	heap.Init(h)
	for _, n := range nums {
		heap.Push(h, n)
		if h.Len() > k {
			heap.Pop(h) // 弹出当前最小的,堆里始终是最大的 K 个
		}
	}
	return *h
}

// 带优先级的任务队列
type Task struct {
	priority int
	name     string
}
type TaskHeap []Task
func (h TaskHeap) Less(i, j int) bool { return h[i].priority > h[j].priority } // 大顶堆 = 高优先级先出

heap 的坑:heap.Pop 弹出的是 h[h.Len()-1]?不——它先把 h[0] 和末尾交换再调你的 Pop()。你的 Pop() 只负责「取出并返回最后一个元素」,排序由 heap 包完成。写错 Pop(比如取 old[0])是经典 bug。

5.3 container/ring:环形缓冲

go
import "container/ring"

// 固定大小的环:滑动窗口、轮转调度
r := ring.New(3)
for i := 0; i < 3; i++ {
	r.Value = i
	r = r.Next()
}

// 遍历(一圈)
r.Do(func(x any) {
	fmt.Println(x) // 0 1 2
})

// 移动与操作
r = r.Move(2)      // 前进 2
r = r.Prev()       // 后退 1
r.Len()            // 3
r.Unlink(1)        // 摘除 n 个节点
r.Link(other, ...) // 插入

// 实战:限长日志环(保留最近 N 条)
type RingLog struct {
	r *ring.Ring
}
func NewRingLog(n int) *RingLog { return &RingLog{r: ring.New(n)} }
func (l *RingLog) Add(line string) {
	l.r.Value = line
	l.r = r.Next() // 覆盖最老的
}
func (l *RingLog) All() []string {
	var out []string
	l.r.Do(func(x any) {
		if x != nil { out = append(out, x.(string)) }
	})
	return out
}

ring 的实际用途比 list/heap 更窄:固定大小的轮转缓冲(时间轮定时器的简化版、轮询调度)。多数「固定大小窗口」用 slice + 取模更直观。

六、flag:命令行解析

go
// 基本用法
func main() {
	name := flag.String("name", "world", "who to greet")
	count := flag.Int("count", 1, "how many times")
	verbose := flag.Bool("v", false, "verbose output")
	duration := flag.Duration("timeout", 30*time.Second, "request timeout")

	flag.Parse() // 必须在访问 flag 值前调用

	for i := 0; i < *count; i++ {
		if *verbose {
			log.Printf("greeting %s", *name)
		}
		fmt.Println("Hello,", *name)
	}
}
bash
./app -name alice -count 3 -v
./app --name=alice -timeout 5s
./app -h    # 自动生成帮助
#  -count int
//    	how many times (default 1)
//  -name string
//    	who to greet (default "world")
//  -timeout duration
//    	request timeout (default 30s)

6.1 进阶:子命令与自定义 flag

go
// 子命令模式(cobra 出现前的标准做法)
func main() {
	switch os.Args[1] {
	case "serve":
		serveCmd := flag.NewFlagSet("serve", flag.ExitOnError)
		port := serveCmd.Int("port", 8080, "port")
		serveCmd.Parse(os.Args[2:])
		serve(*port)
	case "version":
		fmt.Println("v1.0.0")
	default:
		fmt.Println("unknown command")
		os.Exit(1)
	}
}

// flag.ExitOnError vs ContinueOnError(库代码用 Continue,测试可控)
// flag.FlagSet 隔离,避免全局污染

// 自定义 flag 类型:实现 flag.Value 接口
type urlList []string
func (u *urlList) String() string { return strings.Join(*u, ",") }
func (u *urlList) Set(s string) error {
	*u = append(*u, s)
	return nil
}

var urls urlList
flag.Var(&urls, "url", "url to fetch (repeatable)")
flag.Parse()
// ./app -url a.com -url b.com

6.2 flag vs 第三方

库特点
flag(标准库)零依赖,Unix 风格 -flag,无子命令树
spf13/cobra命令树 + flag + 文档生成,CLI 工具事实标准
urfave/cli类似 cobra,API 更轻
pflagPOSIX/GNU 风格 --flag,常配 cobra

简单脚本用 flag;正式 CLI 产品(git 风格多命令)用 cobra。别用 flag 硬造命令树——那个 switch os.Args[1] 超过三个命令就该上 cobra 了。

七、crypto:密码学

7.1 摘要(哈希)

go
import (
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
)

// SHA-256(主流选择)
sum := sha256.Sum256(data)
fmt.Printf("%x\n", sum) // 64 个十六进制字符

// 流式(大文件)
h := sha256.New()
f, _ := os.Open("big.iso")
io.Copy(h, f)
fmt.Printf("%x\n", h.Sum(nil))

// 其他
md5.Sum(data)    // 128 位——仅用于校验和/文件指纹,别用于安全场景
sha1.Sum(data)   // 已破解,仅兼容老系统
sha512.Sum512(data)

// 文件校验和实战
func fileSHA256(path string) (string, error) {
	f, err := os.Open(path)
	if err != nil {
		return "", err
	}
	defer f.Close()
	h := sha256.New()
	if _, err := io.Copy(h, f); err != nil {
		return "", err
	}
	return hex.EncodeToString(h.Sum(nil)), nil
}

7.2 HMAC:带密钥的消息认证

go
import "crypto/hmac"

// 验签:请求参数 + 密钥 → HMAC,比对签名
func sign(secret string, message string) string {
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(message))
	return hex.EncodeToString(mac.Sum(nil))
}

func verify(secret, message, signature string) bool {
	expected := sign(secret, message)
	return hmac.Equal([]byte(expected), []byte(signature)) // 恒定时间比较,防时序攻击
}

hmac.Equal 而不是 ==:== 字符串比较在发现第一个不同字节时就返回,时序差异能被利用逐字节爆破签名。安全场景的 token/签名比对一律用恒定时间比较。

7.3 对称加密:AES-GCM

go
import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
)

// AES-256-GCM:认证加密,防篡改,现代标准选择
func encrypt(key, plaintext []byte) ([]byte, error) {
	block, err := aes.NewCipher(key) // key 必须 16/24/32 字节
	if err != nil {
		return nil, err
	}
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}
	nonce := make([]byte, gcm.NonceSize())
	if _, err := rand.Read(nonce); err != nil { // 真随机,永远别重复
		return nil, err
	}
	// nonce 拼在密文前面,解密时取出
	return gcm.Seal(nonce, nonce, plaintext, nil), nil
}

func decrypt(key, ciphertext []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}
	nonceSize := gcm.NonceSize()
	if len(ciphertext) < nonceSize {
		return nil, errors.New("ciphertext too short")
	}
	nonce, ct := ciphertext[:nonceSize], ciphertext[nonceSize:]
	return gcm.Open(nil, nonce, ct, nil)
}

GCM 的军规:nonce(IV)同一密钥下绝对不能重复——重复 = 认证彻底崩溃(明文可恢复)。用随机 96 位 nonce,或计数器 + 随机盐。

7.4 安全随机数与密码哈希

go
import (
	"crypto/rand"
	"encoding/base64"
)

// 安全随机数:crypto/rand(/dev/urandom),不是 math/rand
token := make([]byte, 32)
if _, err := rand.Read(token); err != nil { // crypto/rand.Read 在 Go 1.20+ 不会失败
	log.Fatal(err)
}
fmt.Println(base64.URLEncoding.EncodeToString(token))

// 会话 ID、CSRF token、密钥生成都用它
// math/rand 只用于:测试数据、洗牌、非安全场景的随机延迟

// 密码存储:bcrypt 或 scrypt(golang.org/x/crypto)
import "golang.org/x/crypto/bcrypt"
hash, _ := bcrypt.GenerateFromPassword([]byte("user password"), bcrypt.DefaultCost)
err := bcrypt.CompareHashAndPassword(hash, []byte("user input")) // nil = 正确

密码学终极建议:业务代码别自己拼加密算法。需要「加密配置」用 KMS;需要「密码存储」用 bcrypt;需要「接口验签」用 HMAC-SHA256。自己发明密码学 = 制造漏洞。

八、常见坑速查

坑后果规则
拷贝带 mutex 的结构体锁失效传指针,开 copylocks 检查
wg.Add 在 goroutine 内Wait 提前返回go 之前 Add
RWMutex 当万能锁写锁饥饿写多用 Mutex
sync.Pool 存连接连接被 GC 关Pool 只放短命对象
heap.Pop 取错元素堆序错乱Pop 只取末尾,heap 包负责交换
用 == 比较签名时序攻击hmac.Equal
AES-GCM nonce 重复加密被破随机 nonce 或计数器
math/rand 生成 token可预测crypto/rand
log.Fatal 在库里杀死宿主进程库只返回 error
float64 存金额精度丢失int64 分 或 big.Rat

下一篇进入并发编程的核心——goroutine 与 channel。

CTO Plus技术栈 Version 1.0.20261024-12