Go Web项目初始化需启用Go Modules并用go mod init创建模块,标准库net/http可直接启动服务,第三方依赖如Chi、Gin等通过go get引入,go.mod和go.sum须提交至Git确保依赖可复现。

用 Go 初始化 Web 项目,核心是正确启用 Go Modules 并引入基础 Web 依赖。不需要 GOPATH,也不依赖外部构建工具,Go 自带的 go mod 就足够。
初始化项目并启用 Go Modules
在空目录中执行:
-
go mod init example.com/myweb—— 替换为你的模块路径(如公司域名或 GitHub 用户名 + 项目名) - 这会生成
go.mod文件,声明模块名和 Go 版本(默认使用当前go version) - 后续所有
go get或go build都会自动记录/更新依赖到go.mod和go.sum
添加标准库 HTTP 服务(无需额外依赖)
Go 标准库 net/http 已足够启动一个基础 Web 服务:
- 新建
main.go,写一个最简 HTTP server:
package main
import (
"fmt"
"log"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello from Go!")
}
func main() {
http.HandleFunc("/", handler)
log.Println("Server starting on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
- 运行
go run main.go即可启动服务,访问http://localhost:8080查看效果 - 此时
go.mod不会新增依赖(因为net/http是标准库)
按需引入常用第三方 Web 依赖
若需路由、中间件、JSON 处理等能力,推荐轻量、主流的库:
立即学习“go语言免费学习笔记(深入)”;
-
Chi(轻量、标准兼容的路由器):
go get github.com/go-chi/chi/v5 -
Gin(高性能、API 友好):
go get github.com/gin-gonic/gin -
SQLx(增强 database/sql):
go get github.com/jmoiron/sqlx -
Logrus(结构化日志):
go get github.com/sirupsen/logrus
每执行一次 go get,Go Modules 会自动下载、记录版本,并写入 go.mod。建议搭配 -u 更新已有包(如 go get -u github.com/go-chi/chi/v5),但生产环境应固定版本以避免意外变更。
验证与日常开发建议
确保依赖可复现、构建可迁移:
- 提交
go.mod和go.sum到 Git(它们是依赖的唯一事实来源) - 本地开发时用
go run .或go build -o myweb .编译 - 清理未使用的依赖:
go mod tidy(自动删掉未引用的包,补全缺失的) - 查看依赖树:
go list -m all或go mod graph | grep chi










