我希望创建一个大型项目,因此需要创建某种文件夹结构。我对Go很陌生,但是据我了解,这样做的方法是创建包,对吗?我正在使用Go模块,我尝试了许多在此处和在Google上找到的不同解决方案,但是似乎没有一个适合我。

我现在想要的只是将example.go文件中的导出功能导入main.go

文件夹结构如下:

client
example
---example.go
go.mod
go.sum
main.go
  1. 我已经使用go mod init创建了模块文件,请参见下面的第一个代码段
  2. 第二个代码段显示main.go的header的样子
  3. 第三个片段是具有我要导入功能的软件包
    module exampleapp
    go 1.12
    require (
        github.com/gin-gonic/contrib v0.0.0-20190408155029-b5986969cb50
        github.com/gin-gonic/gin v1.4.0
    )

package main
import (
    "net/http"
    "exampleapp/example"
)
    package example
    import (
        "net/http"
        "github.com/gin-gonic/gin"
    )

    func GetAllEmployees(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "message": "pong",
        })
    }

在大多数情况下,当我尝试在main.go中添加软件包时,VSCode会自动删除该行,并且在main函数中显示未定义GetAllEmployees。我设法在删除软件包之前捕获了错误的软件包,它说-

"imported and not used: "exampleapp/example"
Am I wrong to use "exampleapp/example" module name exampleapp here? I tried without the exampleapp and "./example/example", but then I get an error that says it cannot find module for path.

非常感谢您的帮助,因为我在此问题上停留了很长时间,无法弄清楚,我在这里缺少什么。

分析解答

应该是这样的(main.go):

package main
import (
    "exampleapp/example"
)

func main() {
    example.GetAllEmployees(...)
}