duanli8577 2019-05-19 16:23
浏览 102
已采纳

使用Go模块时如何导入本地软件包

I wish to create a large project, so I need to create some kind of folder structure. I am quite new to Go, but, as I understand, the way to do it is to create packages, right? I am using Go modules, I have tried many different solutions found here and on Google, but none of them seem to work for me.

All I want to for now, is import exported function from example.go file into main.go

Folder structure is as follows:

client
example
---example.go
go.mod
go.sum
main.go
  1. I have created module file with go mod init, see the first code snippet below
  2. Second code snippet shows how the header of main.go looks like
  3. Third snippet is the package with the function I want to import
    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",
        })
    }

For the most part, when I try to add package in main.go, VSCode automatically removes the line and in the main function says that GetAllEmployees is not defined. I managed to catch error package before the package is removed, it says -

"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.

Help would be highly appreciated, as I have been stuck on this for quite some time and can't figure out, what am I missing here.

  • 写回答

1条回答 默认 最新

  • doupo1865 2019-05-19 16:42
    关注

    It should be like that (main.go):

    package main
    import (
        "exampleapp/example"
    )
    
    func main() {
        example.GetAllEmployees(...)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?