Skip to content

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/httpHTTP 客户端与服务端
net/urlURL 解析与编码
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/jsonJSON 编解码
encoding/xmlXML 编解码
encoding/csvCSV 读写
encoding/base64Base64 编解码
encoding/gobGo 专属二进制序列化
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/tlsTLS 配置
crypto/rand密码学安全随机数
crypto/hmacHMAC 签名
go
h := sha256.Sum256([]byte("hello"))
fmt.Printf("%x\n", h)

// 安全随机
b := make([]byte, 16)
crypto_rand.Read(b)

并发

用途
syncWaitGroup、Mutex、Once、Map、Pool
sync/atomic原子操作(无锁计数)
context取消、超时、请求范围值
go
var counter int64
atomic.AddInt64(&counter, 1)
v := atomic.LoadInt64(&counter)

测试

用途
testing单元测试、基准测试、子测试
net/http/httptestHTTP 处理器测试
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/utf8UTF-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反射
runtimeruntime 信息(GOMAXPROCS、goroutine 数)

作者:yanshaodong