One - One Code All

Blog Content

golang gin框架测试hello world

Linux-Mac Go   2020-06-03 08:25:42

新建代码目录gin-test。

目录下创建文件:go.mod  内容为:

module gin-test

go 1.20

在项目根目录执行

go get -u github.com/gin-gonic/gin

如果time out 则更换为国内源,执行

export GOPROXY=https://goproxy.cn,direct

再执行上一步,这时可以看到执行成功,go.mod文件里追加了一些代码 require ( )。


建立主文件main.go

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	r := gin.Default()
	//定义路由的GET方法及响应处理函数
	r.GET("/hello", func(c *gin.Context) {
		//将发送的信息封装成JSON发送给浏览器
		c.JSON(http.StatusOK, gin.H{
			//这是我们定义的数据
			"message": "快速入门",
		})
	})
	r.Run() //默认在本地8080端口启动服务
}

 然后,执行go run main.go命令来运行代码。在浏览器中输入127.0.0.1:8080/hello访问,查看结果。


上一篇:Grafana+Prometheus实现Ceph监控和钉钉告警
下一篇:使用Harbor自建企业级Docker镜像仓库

The minute you think of giving up, think of the reason why you held on so long.