golang使用Gin框架搭建服务器时报错go.mod file not found in current directory or any parent directory

2022-06-21 09:29:19

golang使用Gin框架搭建服务器时报错go.mod file not found in current directory or any parent directory 找不到对应的包

原因:没有生成go.mod文件

在解决问题之前,确保系统环境变量有如下设置
在这里插入图片描述

流程分析

编写test.go文件

package mainimport("github.com/gin-gonic/gin")funcsayhello(c*gin.Context){
	c.JSON(200, gin.H{"message":"hello golang",})}funcmain(){
	r:= gin.Default()

	r.GET("/hello", sayhello)

	r.Run(":8080")}

运行时,报错go.mod file not found in current directory or any parent directory,这是由于缺少go.mod文件导致的。

查看错误提示如下:
在这里插入图片描述
-----这是由于我们使用了go module方式实现依赖,由于设置了环境变量GO111MODULE=on,所以编译器会自动忽略gopath目录下的包,同时又没有go.mod文件配置相关的导入包,所以编译器报错找不到"github.com/gin-gonic/gin"。

解决方法如下:
①win+R 打开cmd进入到test.go所在的文件目录下
在这里插入图片描述
②输入go mod init +“文件名称”,例子中文件名称为test.go,所以我们输入go mod init test回车运行后会在当前目录下生成一个go.mod文件
在这里插入图片描述

方法一:打开cmd,进入到test.go的文件目录下,输入go get github.com/gin-gonic/gin回车运行,会再次生成一个go.sum文件(此方法适用于还未下载gin包到pkg目录下的情况,当然,如果已经下载过,此方法也适用)
在这里插入图片描述
方法二:打开cmd,在test.go文件的当前目录下输入go mod tidy(此方法适用于已经将gin包下载到pkg文件夹中)
在这里插入图片描述
go.sum文件如下:
在这里插入图片描述
③之后,再次回到编译器运行hello.go文件
在这里插入图片描述
无报错,服务器成功打开,打开网页进行测试:

在这里插入图片描述
服务器正常运行,问题解决

结尾相关

如果想要详细了解gin框架相关的内容以及go mod和go sum等知识,可以阅览,https://blog.csdn.net/weixin_48860459/article/details/106954017

  • 作者:小小小小怪下士
  • 原文链接:https://blog.csdn.net/qq_42805782/article/details/119544406
    更新时间:2022-06-21 09:29:19