主题
Go 标准库速览
Go 标准库极其丰富,覆盖了网络、编码、并发、测试等绝大多数服务端开发需求。本文按分类列出常用包及典型用法,供快速查阅。
输入输出
| 包 | 用途 |
|---|---|
fmt | 格式化输入输出(Println / Sprintf / Scanf) |
io | 通用 I/O 原语(Reader / Writer 接口) |
io/ioutil | (旧)读写文件,Go 1.16 起建议用 os / io 替代 |
os | 操作系统交互、文件、环境变量 |
bufio | 带缓冲的 I/O,提升读写性能 |
path/filepath | 跨平台文件路径处理 |
go
// 读取文件全部内容
data, err := os.ReadFile("config.json")
if err != nil {
return err
}
// 带缓冲写入
f, _ := os.Create("out.txt")
defer f.Close()
w := bufio.NewWriter(f)
w.WriteString("hello")
w.Flush()网络
| 包 | 用途 |
|---|---|
net | 底层网络(TCP/UDP、DNS 解析) |
net/http | HTTP 客户端与服务端 |
net/url | URL 解析与编码 |
go
// 发起 GET 请求
resp, err := http.Get("https://api.example.com/users")
if err != nil {
return err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
// 启动 HTTP 服务
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello")
})
http.ListenAndServe(":8080", nil)编码
| 包 | 用途 |
|---|---|
encoding/json | JSON 编解码 |
encoding/xml | XML 编解码 |
encoding/csv | CSV 读写 |
encoding/base64 | Base64 编解码 |
encoding/gob | Go 专属二进制序列化 |
go
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
// 序列化
data, _ := json.Marshal(User{Name: "Tom", Age: 20})
// 反序列化
var u User
json.Unmarshal(data, &u)加密与安全
| 包 | 用途 |
|---|---|
crypto | 加密原语基础 |
crypto/md5 / crypto/sha256 | 哈希 |
crypto/tls | TLS 配置 |
crypto/rand | 密码学安全随机数 |
crypto/hmac | HMAC 签名 |
go
h := sha256.Sum256([]byte("hello"))
fmt.Printf("%x\n", h)
// 安全随机
b := make([]byte, 16)
crypto_rand.Read(b)并发
| 包 | 用途 |
|---|---|
sync | WaitGroup、Mutex、Once、Map、Pool |
sync/atomic | 原子操作(无锁计数) |
context | 取消、超时、请求范围值 |
go
var counter int64
atomic.AddInt64(&counter, 1)
v := atomic.LoadInt64(&counter)测试
| 包 | 用途 |
|---|---|
testing | 单元测试、基准测试、子测试 |
net/http/httptest | HTTP 处理器测试 |
testing/quick | 基于属性的测试 |
go
func TestAdd(t *testing.T) {
if got := add(1, 2); got != 3 {
t.Errorf("add(1,2) = %d, want 3", got)
}
}
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
add(1, 2)
}
}时间与字符串
| 包 | 用途 |
|---|---|
time | 时间、定时器、时区 |
strings | 字符串操作 |
strconv | 字符串与基本类型互转 |
regexp | 正则表达式 |
unicode/utf8 | UTF-8 编解码 |
go
now := time.Now()
later := now.Add(24 * time.Hour)
fmt.Println(now.Format("2006-01-02 15:04:05"))
s := strings.Join([]string{"a", "b", "c"}, "-") // a-b-c
n, _ := strconv.Atoi("42")Go 时间格式化使用固定参考时间
2006-01-02 15:04:05(即 01/02 03:04:05PM 06-07 布局),而非YYYY-MM-DD。
数据库
| 包 | 用途 |
|---|---|
database/sql | 通用 SQL 数据库接口 |
database/sql/driver | 驱动接口(供驱动实现) |
go
db, _ := sql.Open("mysql", dsn)
var name string
db.QueryRow("SELECT name FROM users WHERE id = ?", 1).Scan(&name)实际项目中通常使用第三方驱动(如
github.com/go-sql-driver/mysql)与 ORM(如 GORM)。
其他常用包
| 包 | 用途 |
|---|---|
flag | 命令行参数解析 |
log / log/slog | 日志(slog 为 Go 1.21+ 结构化日志) |
sort | 排序 |
math / math/rand | 数学与伪随机数 |
reflect | 反射 |
runtime | runtime 信息(GOMAXPROCS、goroutine 数) |
作者:yanshaodong