Linux环境安装go部署运行gin框架
1、Centos7.9解压安装go1.18
[root@node01 09:21:08/usr/local]#cd /usr/local/ && tar xf go1.18.1.linux-amd64.tar.gz
2、添加环境变量
vim /etc/profile export GOROOT=/usr/local/go export PATH=$GOROOT/bin:$PATH
3、检查是否成功
[root@master 09:12:24 /data/go/gin_demo]# go version go version go1.18.1 linux/amd64
4、初始化mod
# 创建web目录
mkdir /data/go/gin_demo
# 初始化mod 用来管理go的依赖包
[root@node01 09:50:39/data/go/gin_demo]# go mod init gin
go: creating new go.mod: module gin
go: to add module requirements and sums:
go mod tidy
# 走国内代理下载
[root@node01 09:51:49/data/go/gin_demo]# go env -w GOPROXY=https://goproxy.cn,direct
# 下载gin包,这是一个web框架
[root@node01 09:51:10/data/go/gin_demo]# go get github.com/gin-gonic/gin
5、编写main.go文件
[root@node01 09:38:40/data/go/gin_demo]# vim main.go
package main
import "github.com/gin-gonic/gin"
func sayHello(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Hello golang!",
})
}
func main() {
r := gin.Default() // 返回默认的路由引擎
r.GET("/hello", sayHello)
// 启动服务
r.Run()
}
6、运行是否成功
[root@node01 09:52:55/data/go/gin_demo]# go run main.go [GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached. [GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode) [GIN-debug] GET /hello --> main.sayHello (3 handlers) [GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value. Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details. [GIN-debug] Environment variable PORT is undefined. Using port :8080 by default [GIN-debug] Listening and serving HTTP on :8080
7、访问测试


浙公网安备 33010602011771号