Skip to content

Go 常用库使用指南

Go 内置标准库与常见外部库的快速上手。

Updated View as Markdown

Go 常用库

本文介绍 Go 内置标准库与常见外部库的基本用法,帮助你快速上手开发。

标准库

Go 自带的 stdlib 无需额外依赖,本节按用途分类介绍最常用的包。

格式化与字符串

fmt 是最常用的库之一,用于打印与格式化字符串。

package main

import "fmt"

func main() {
	name, age := "Alice", 30
	// Printf 按格式串输出
	fmt.Printf("%s is %d years old\n", name, age)

	// Sprintf 返回格式化字符串
	msg := fmt.Sprintf("Hello, %s!", name)
	fmt.Println(msg)
}

常用动词:%s 字符串、%d 整数、%f 浮点数、%v 任意值(默认格式)、%q 带引号字符串。

strings 提供字符串的查询、拆分、大小写转换等操作。

import (
	"fmt"
	"strings"
)

func main() {
	s := "hello, world"
	fmt.Println(strings.HasPrefix(s, "hello")) // true
	fmt.Println(strings.ToUpper(s))            // HELLO, WORLD
	fmt.Println(strings.Split(s, ","))         // [hello  world]
	fmt.Println(strings.TrimSpace("  hi  "))   // hi
	fmt.Println(strings.Contains(s, "world"))  // true
}

strconv 负责字符串与数值之间的互转。

import (
	"fmt"
	"strconv"
)

func main() {
	n, err := strconv.Atoi("42") // 字符串转 int
	if err != nil {
		return
	}
	fmt.Println(n + 1) // 43

	s := strconv.Itoa(n) // int 转字符串,s == "42"

	f, _ := strconv.ParseFloat("3.14", 64) // 3.14
	_ = s
	_ = f
}

时间、文件与 IO

time 提供时间获取、格式化、解析与计算。注意 Go 的格式化参考时间是 2006-01-02 15:04:05

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	fmt.Println(now.Format("2006-01-02 15:04:05"))

	// 解析时间
	t, _ := time.Parse("2006-01-02", "2026-08-05")
	fmt.Println(t.Weekday())

	// 时间计算
	after := now.Add(3 * time.Hour)
	fmt.Println(after.Sub(now)) // 3h0m0s

	// 定时器
	timer := time.NewTimer(1 * time.Second)
	<-timer.C
	fmt.Println("1 秒已过")
}

os 负责文件读写、环境变量与系统操作。

import (
	"fmt"
	"os"
)

func main() {
	// 写文件
	if err := os.WriteFile("hello.txt", []byte("Hello Go"), 0644); err != nil {
		panic(err)
	}

	// 读文件
	data, err := os.ReadFile("hello.txt")
	if err != nil {
		panic(err)
	}
	fmt.Println(string(data))

	// 环境变量
	home := os.Getenv("HOME")
	fmt.Println(home)
}

io 是输入输出底层接口,常与 strings.Readerbytes.Buffer 等组合使用。

import (
	"fmt"
	"io"
	"strings"
)

func main() {
	r := strings.NewReader("hello io")
	buf := make([]byte, 16)

	n, err := r.Read(buf)
	if err != nil && err != io.EOF {
		return
	}
	fmt.Printf("读取 %d 字节:%s\n", n, buf[:n])
}

JSON 与 HTTP

encoding/json 提供 JSON 的编解码,配合结构体 tag 使用。

import (
	"encoding/json"
	"fmt"
)

type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	// 结构体 → JSON
	u := User{Name: "Bob", Age: 25}
	data, _ := json.Marshal(u)
	fmt.Println(string(data)) // {"name":"Bob","age":25}

	// JSON → 结构体
	var v User
	if err := json.Unmarshal(data, &v); err != nil {
		return
	}
	fmt.Println(v.Name) // Bob
}

net/http 同时支持 HTTP 服务端与客户端。

import (
	"fmt"
	"net/http"
)

func main() {
	// HTTP 服务端
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, %s!", r.URL.Path)
	})
	go http.ListenAndServe(":8080", nil)

	// HTTP 客户端
	resp, err := http.Get("http://localhost:8080/")
	if err != nil {
		return
	}
	defer resp.Body.Close()
	fmt.Println(resp.Status) // 200 OK
}

sync 提供并发安全原语,如互斥锁与协程同步。

import (
	"fmt"
	"sync"
)

func main() {
	var mu sync.Mutex
	var wg sync.WaitGroup
	count := 0

	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			mu.Lock()
			count++
			mu.Unlock()
		}()
	}
	wg.Wait()
	fmt.Println(count) // 100
}

常见外部库

gin

高性能 Web 框架,适合快速构建 RESTful API。

gorm

功能完善的 ORM,支持多种数据库驱动。

viper

配置管理库,支持 YAML / JSON / 环境变量等。

zap

Uber 出品的高性能日志库。

cobra

命令行应用框架,广泛用于 CLI 工具。

testify

测试断言与 mock 工具,简化单元测试。

gin — Web 框架

go get github.com/gin-gonic/gin
import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()

	r.GET("/ping", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"message": "pong"})
	})

	r.Run(":8080")
}

gorm — ORM

go get gorm.io/gorm gorm.io/driver/sqlite
import (
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

type Product struct {
	gorm.Model
	Name  string
	Price float64
}

func main() {
	db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	db.AutoMigrate(&Product{})

	// 创建
	db.Create(&Product{Name: "鼠标", Price: 99.9})

	// 查询
	var p Product
	db.First(&p, "name = ?", "鼠标")
}

viper — 配置管理

go get github.com/spf13/viper
import "github.com/spf13/viper"

func main() {
	viper.SetDefault("port", 8080) // 默认值
	viper.SetConfigName("config")  // config.yaml
	viper.SetConfigType("yaml")
	viper.AddConfigPath(".")

	if err := viper.ReadInConfig(); err != nil {
		return
	}
	_ = viper.GetInt("port")
}

zap — 日志

go get go.uber.org/zap
import "go.uber.org/zap"

func main() {
	logger, _ := zap.NewProduction()
	defer logger.Sync()

	logger.Info("服务启动",
		zap.String("env", "prod"),
		zap.Int("port", 8080),
	)
}

cobra — CLI 命令行

go get github.com/spf13/cobra
import (
	"fmt"

	"github.com/spf13/cobra"
)

func main() {
	rootCmd := &cobra.Command{
		Use:   "app",
		Short: "示例 CLI 应用",
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Println("Hello from CLI!")
		},
	}
	rootCmd.Execute()
}

testify — 单元测试断言

go get github.com/stretchr/testify
import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func Add(a, b int) int { return a + b }

func TestAdd(t *testing.T) {
	assert.Equal(t, 4, Add(2, 2))
	assert.NotEqual(t, 5, Add(2, 2))
}

依赖管理

初始化模块

go mod init mymodule

安装依赖

go get github.com/gin-gonic/gin

整理依赖并运行测试

go mod tidy
go test ./...

小结

  • 标准库满足大部分基础需求,优先使用内置库避免引入额外依赖。
  • 外部库按需引入,用 go get 安装并写入 go.mod
  • 使用 <Icon name="ph:go" /> 或从 astro-icon 选择图标,为文档页增加视觉标识。
Navigation

Type to search…

↑↓ navigate↵ selectEsc close