为gin框架配置热加载,可以引入codegangsta/gin工具
1.安装gin框架热加载工具
go install github.com/codegangsta/gin@latest
2.配置gin环境变量
在/etc/profile中添加($GOPATH是已经配置好的go目录,即gin会被安装的位置)
export PATH=$PATH:$GOPATH/bin
完整配置参考
export GOROOT=/usr/local/go ##Golang安装目录
export PATH=$GOROOT/bin:$PATH
export GOPATH=/home/liubai/golang ##Golang项目目录
export PATH=$PATH:$GOPATH/bin
3.测试是否安装成功
# 正常返回则安装成功
gin help
返回示例
liubai@liubai:~/golang/src/AIAssistant$ go help
Go is a tool for managing Go source code.
Usage:
go <command> [arguments]
The commands are:
bug start a bug report
build compile packages and dependencies
clean remove object files and cached files
doc show documentation for package or symbol
env print Go environment information
fix update packages to use new APIs
fmt gofmt (reformat) package sources
generate generate Go files by processing source
get add dependencies to current module and install them
install compile and install packages and dependencies
list list packages or modules
mod module maintenance
work workspace maintenance
run compile and run Go program
telemetry manage telemetry data and settings
test test packages
tool run specified go tool
version print Go version
vet report likely mistakes in packages
Use "go help <command>" for more information about a command.
Additional help topics:
buildconstraint build constraints
buildmode build modes
c calling between Go and C
cache build and test caching
environment environment variables
filetype file types
go.mod the go.mod file
gopath GOPATH environment variable
goproxy module proxy protocol
importpath import path syntax
modules modules, module versions, and more
module-auth module authentication using go.sum
packages package lists and patterns
private configuration for downloading non-public code
testflag testing flags
testfunc testing functions
vcs controlling version control with GOVCS
Use "go help <topic>" for more information about that topic.
4.使用gin启动服务
# 访问4443会被代理到8888 不可重复
gin -p 4443 -a 8888 -b gin-bin --all run
启动后4443和8888均可访问
5.main示例
package main
import "github.com/gin-gonic/gin"
func main() {
// 创建服务
ginServer := gin.Default()
ginServer.GET("/ping", func(conetext *gin.Context) {
conetext.JSON(200, gin.H{
"message": "ping",
})
})
ginServer.POST("/post", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{
"message": "post",
})
})
// 监听并在 0.0.0.0:8888 上启动gin服务
ginServer.Run(":8888")
}
6.启停脚本
启
gin -p 4443 -a 8888 -b gin-bin --all run
停
#!/bin/bash
# 检查是否有程序在监听 4443 端口
#!/bin/bash
# 检查是否有程序在监听 4443 端口 自定义的gin端口
if lsof -i :4443 | grep LISTEN | grep -q 'gin'; then
# 获取监听 4443 端口的程序名为 gin,使用 kill -9 终止该程序
pid=$(lsof -i :4443 | grep LISTEN | grep 'gin' | awk '{print $2}')
kill -9 $pid
echo "进程 $pid 已被终止"
else
echo "未找到监听 4443 端口且名称为 gin 的程序"
fi
# 检查是否有程序在监听 8888 端口 自定义的服务端口
if lsof -i :8888 | grep LISTEN | grep -q 'gin-bin'; then
# 获取监听 4443 端口的程序名为 gin,使用 kill -9 终止该程序
pid=$(lsof -i :8888 | grep LISTEN | grep 'gin-bin' | awk '{print $2}')
kill -9 $pid
echo "进程 $pid 已被终止"
else
echo "未找到监听 8888 端口且名称为 gin-bin 的程序"
fi