首先要配置代理,就像maven配置国内源一样,有效提升下载速度
GOPROXY=https://goproxy.io
然后就可以执行
go get -u github.com/gin-gonic/gin
如果还是报错超时, 那么可以先执行一下两条命令再次重试下载
go env -w GOPROXY=https://goproxy.cn,direct
go mod tidy
效果如下:
package main
import "github.com/gin-gonic/gin"
func main() {
//创建一个服务
ginServer := gin.Default()
//创建GET请求
ginServer.GET("hello", func(context *gin.Context) {
//响应code,返回内容
context.JSON(200, gin.H{"msg": "hello world"})
})
//端口
ginServer.Run(":8888")
}
postman测试:(也可以直接在浏览器访问. )
----------------------------------
返回前端页面:
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
//创建一个服务
ginServer := gin.Default()
//全局加载页面
ginServer.LoadHTMLGlob("templates/*")
//指定加载
//ginServer.LoadHTMLFiles("templates/index.html")
//html
ginServer.GET("index", func(context *gin.Context) {
context.HTML(http.StatusOK, "index.html", gin.H{
"msg": "这是来自go后端传输的数据",
})
})
//端口
ginServer.Run(":8888")
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>my first page</title>
</head>
<body>
<h1>hello wsc</h1>
获取内容:
{{.msg}}
</body>
</html>
项目文件目录如下:
访问localhost:8888/index
另外还发现一个问题, 如果端口设置(ginServer.Run(":8888"))放在GET请求前面会导致404报错...
看了另一位小哥的文章发现 gin配置的Run方法一定要放在最后...