前言 我们在使用gin开发web项目的时候,传统的运行方式:使用gorunapp。go去运行自己的项目。但是在开发过程中,每改一次代码,都要进行一次重启,那在go中如何使用热加载呢?什么是热加载 热加载在开发过程中,改动代码或新增代码时自动加载更新内容并重新发布。热加载有以下用处:自动加载更新内容自动发布更新内容提高开发效率,专注业务开发,而不需要反复重启应用进行调试接口安装fresh Fresh是一个命令行工具,它会在您每次保存Go或模板文件时构建和(重新)启动您的Web应用程序。 如果您使用的Web框架支持Freshrunner,它会在您的浏览器上显示构建错误。 传送门:freshgithub 安装fresh 前置条件:必须有go环境。 查看go版本:goversiongoversiongo1。18。1darwinamd64 安装freshgogetgithub。compilufresh使用fresh进行热加载 在传统的开发中,运行go程序,是通过gorunmain。go命令运行的,使用了fresh之后,运行方式有所变更,直接命令fresh就可以了。chatginfresh22:33:52runnerInitFolders22:33:52runnermkdir。tmp22:33:52runnermkdir。tmp:fileexists22:33:52watcherWatching。22:33:52watcherWatchingevn22:33:52watcherWatchingsrc22:33:52watcherWatchingsrcauthenticate22:33:52watcherWatchingsrccommon22:33:52watcherWatchingsrcconfig22:33:52watcherWatchingsrcinterfaces22:33:52watcherWatchingsrcmodule22:33:52watcherWatchingsrcrouter22:33:52watcherWatchingsrcservice22:33:52watcherWatchingsrctables22:33:52watcherWatchingsrcutils22:33:52mainWaiting(loop1)。。。22:33:52mainreceivingfirstevent22:33:52mainsleepingfor600milliseconds22:33:53mainflushingevents22:33:53mainStarted!(38Goroutines)22:33:53mainremovetmprunnerbuilderrors。log:nosuchfileordirectory22:33:53buildBuilding。。。22:33:53runnerRunning。。。22:33:53main22:33:53mainWaiting(loop2)。。。22:33:53app〔GINdebug〕〔WARNING〕CreatinganEngineinstancewiththeLoggerandRecoverymiddlewarealreadyattached。〔GINdebug〕〔WARNING〕Runningindebugmode。Switchtoreleasemodeinproduction。usingenv:exportGINMODEreleaseusingcode:gin。SetMode(gin。ReleaseMode)22:33:53app〔GINdebug〕POSTauthloginorg。chatginsrcrouter。Router。func1(5handlers)22:33:53app〔GINdebug〕POSTuserregisterorg。chatginsrcrouter。Router。func2(5handlers)〔GINdebug〕〔WARNING〕Youtrustedallproxies,thisisNOTsafe。Werecommendyoutosetavalue。Pleasecheckhttps:pkg。go。devgithub。comgingonicginreadmedonttrustallproxiesfordetails。〔GINdebug〕ListeningandservingHTTPon:8080问题处理 安装错误 在Mac上安装fresh时,发生以下错误:xxxMacBookProgogetgithub。compilufreshpackagegolang。orgxsysunix:unrecognizedimportpathgolang。orgxsysunix:httpsfetch:Gethttps:golang。orgxsysunix?goget1:dialtcp142。251。43。17:443:iotimeout 当出现上面的问题时,按提示要求先importgolang。orgxsysunix,如何在GOPATH下导入这个依赖呢?进入GOPATH目录cdGOPATHsrc创建golang。orgx目录mkdirpgolang。orgx进入golang。orgxcdgolang。orgx下载源码gitclonehttps:github。comgolangsys。git 等待下载完成,就完成了golang。orgxsysunix的导入,然后在GOPATH重新运行gogetgithub。compilufresh就可以了。 fresh运行:commandnotfoundfresh错误 设置环境变量:修改环境变量vim。zshrcaddconfigexportGOROOTusrlocalgoexportGOPATHUsersxxxxxxxxgoworkspaceexportPATHPATH:GOROOTbin:GOPATHbin让设置生效source。zshrc