七爪源码:这是在 Go 中进行实时重新加载的好方法
ztj100 2025-07-23 19:25 2 浏览 0 评论
在你的项目中只是“空气”
如果你从 Node.js 进入 Go 世界,你可能会错过 JavaScript、Angular、React、Vue 等中的一项重要功能。
它们都可以快速开发,因为它们会在您保存正在处理的文件时进行更改,当您使用诸如 express 之类的东西时也会发生同样的事情,有诸如 nodemon 之类的工具可以使这项工作变得容易。
在 Go 中,有多种方法可以实现这一点。在我看来,我将展示其中一个,最好的一个。我还将向您描述仅使用 Go 应用程序或 docker-compose 文件中的其他依赖项来执行此操作。
此方法适用于 go 模块。此外,如果您使用 go get 添加新的依赖项,该应用程序也将重新加载。
目录
本教程分为以下主题:
- 示例 go 应用程序(带有 go 模块)
- Live-Reload 单个应用程序
- 具有多个依赖项的实时重新加载(docker-compose)
示例应用程序
这个简单的应用程序包含 2 个文件,main.go 和 go.mod,它只是在您每次按 enter 时打印一个随机数 uuid。
module github.com/luisegr/go-live-reload-tutorial
go 1.17
require github.com/google/uuid v1.3.0 // indirect
package main
import (
"fmt"
"time"
"github.com/google/uuid"
)
func main() {
for {
id := uuid.New()
fmt.Println("This is the new id: ", id.String())
time.Sleep(4 * time.Second)
}
}
这个简单的程序每 4 秒生成一个新的 UUID 并将其显示在控制台中,很容易不会分散我们的主要目标:实时重载。
Live Reload - 单个应用程序
为了使用实时重载(重新构建并在保存时重新运行)获取此应用程序,我们需要安装 Air:
go install github.com/cosmtrek/air@latest
这将直接从 Air 存储库安装它。 之后,我们可以通过运行 air -v 来测试安装。
然后我们可以进入我们的应用目录并初始化它:
air init
这将创建一个具有默认值的文件 .air.toml。 您可以查看并修改应用程序所需的内容(构建命令、排除文件夹等)。
它看起来像这样:
root = "."
testdata_dir = "testdata"
tmp_dir = "tmp"
[build]
bin = "./tmp/main"
cmd = "go build -o ./tmp/main ."
delay = 1000
exclude_dir = ["assets", "tmp", "vendor", "testdata"]
exclude_file = []
exclude_regex = ["_test.go"]
exclude_unchanged = false
follow_symlink = false
full_bin = ""
include_dir = []
include_ext = ["go", "tpl", "tmpl", "html"]
kill_delay = "0s"
log = "build-errors.log"
send_interrupt = false
stop_on_error = true
[color]
app = ""
build = "yellow"
main = "magenta"
runner = "green"
watcher = "cyan"
[log]
time = false
[misc]
clean_on_exit = false
[screen]
clear_on_rebuild = false
初始化完成后,我们可以开始使用刚刚运行的 live-reload:
air
现在,如果我们对应用程序进行任何更改,它将检测、编译并运行它。 在这个例子中,我只是测试了改变它等待每个 UUID 生成的秒数:
我们也可以在不安装 air 的情况下通过 docker 容器将其归档,只需使用 air docker 映像运行它:
docker run -it — rm \
-w "/go/src/github.com/luisegr/go-live-reload-tutorial" \
-v $(pwd):/go/src/github.com/luisegr/go-live-reload-tutorial \
cosmtrek/air
这将导致相同的输出并在更改时重新加载:
Live-Reload - 多个依赖项
如果您正在使用 docker-compose 运行您的开发环境,并且您正在使用其他东西,如 postgres、mongo、Redis 等。与您的应用程序一起,您还可以使用 Air 进行实时重新加载。
你只需要像这样设置你的 docker-compose.yml :
version: "3.3"
services:
mongodb:
image : mongo
container_name: mongo-my-app
ports:
- 27018:27017
restart: always
volumes:
- mongo-vol:/data/db
environment:
- MONGO_INITDB_ROOT_USERNAME=user
- MONGO_INITDB_ROOT_PASSWORD=pass
## Postgres, redis, minio, etc ...
my-app:
image: cosmtrek/air
# working_dir value has to be the same of mapped volume
working_dir: /project
ports:
- 8000:8000
volumes:
- ./:/project/
links:
- mongodb
container_name: my-app
environment:
- PORT=8000
- MONGO_HOST=mongodb
- MONGO_USER=user
- MONGO_PASSWORD=pass
- MONGO_PORT=27018
- MONGO_DATABASE=test
volumes:
mongo-vol:
然后你可以像往常一样运行你的应用程序:
docker-compose up
您将看到输出,如果您仍然具有实时重新加载功能:
希望这个对你有帮助
相关推荐
- 10条军规:电商API从数据泄露到高可用的全链路防护
-
电商API接口避坑指南:数据安全、版本兼容与成本控制的10个教训在电商行业数字化转型中,API接口已成为连接平台、商家、用户与第三方服务的核心枢纽。然而,从数据泄露到版本冲突,从成本超支到系统崩溃,A...
- Python 文件处理在实际项目中的困难与应对策略
-
在Python项目开发,文件处理是一项基础且关键的任务。然而,在实际项目中,Python文件处理往往会面临各种各样的困难和挑战,从文件格式兼容性、编码问题,到性能瓶颈、并发访问冲突等。本文将深入...
- The Future of Manufacturing with Custom CNC Parts
-
ThefutureofmanufacturingisincreasinglybeingshapedbytheintegrationofcustomCNC(ComputerNumericalContro...
- Innovative Solutions in Custom CNC Machining
-
Inrecentyears,thelandscapeofcustomCNCmachininghasevolvedrapidly,drivenbyincreasingdemandsforprecisio...
- C#.NET serilog 详解(c# repository)
-
简介Serilog是...
- Custom CNC Machining for Small Batch Production
-
Inmodernmanufacturing,producingsmallbatchesofcustomizedpartshasbecomeanincreasinglycommondemandacros...
- Custom CNC Machining for Customized Solutions
-
Thedemandforcustomizedsolutionsinmanufacturinghasgrownsignificantly,drivenbydiverseindustryneedsandt...
- Revolutionizing Manufacturing with Custom CNC Parts
-
Understandinghowmanufacturingisevolving,especiallythroughtheuseofcustomCNCparts,canseemcomplex.Thisa...
- Breaking Boundaries with Custom CNC Parts
-
BreakingboundarieswithcustomCNCpartsinvolvesexploringhowadvancedmanufacturingtechniquesaretransformi...
- Custom CNC Parts for Aerospace Industry
-
Intherealmofaerospacemanufacturing,precisionandreliabilityareparamount.Thecomponentsthatmakeupaircra...
- Cnc machining for custom parts and components
-
UnderstandingCNCmachiningforcustompartsandcomponentsinvolvesexploringitsprocesses,advantages,andcomm...
- 洞察宇宙(十八):深入理解C语言内存管理
-
分享乐趣,传播快乐,增长见识,留下美好。亲爱的您,这里是LearingYard学苑!今天小编为大家带来“深入理解C语言内存管理”...
- The Art of Crafting Custom CNC Parts
-
UnderstandingtheprocessofcreatingcustomCNCpartscanoftenbeconfusingforbeginnersandevensomeexperienced...
- Tailored Custom CNC Solutions for Automotive
-
Intheautomotiveindustry,precisionandefficiencyarecrucialforproducinghigh-qualityvehiclecomponents.Ta...
- 关于WEB服务器(.NET)一些经验累积(一)
-
以前做过技术支持,把一些遇到的问题累积保存起来,现在发出了。1.问题:未能加载文件或程序集“System.EnterpriseServices.Wrapper.dll”或它的某一个依赖项。拒绝访问。解...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- 10条军规:电商API从数据泄露到高可用的全链路防护
- Python 文件处理在实际项目中的困难与应对策略
- The Future of Manufacturing with Custom CNC Parts
- Innovative Solutions in Custom CNC Machining
- C#.NET serilog 详解(c# repository)
- Custom CNC Machining for Small Batch Production
- Custom CNC Machining for Customized Solutions
- Revolutionizing Manufacturing with Custom CNC Parts
- Breaking Boundaries with Custom CNC Parts
- Custom CNC Parts for Aerospace Industry
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)