dongyi1996 2019-04-11 11:36
浏览 2210
已采纳

go mod:找不到提供包的模块

I am creating a go project with version 1.12.1. If I run GOPATH="$(pwd)/vendor:$(pwd)" GOBIN="$(pwd)/bin" go clean I get the following error:

can't load package: package github.com/marvincaspar/go-example: unknown import path "github.com/marvincaspar/go-example": cannot find module providing package github.com/marvincaspar/go-example

This is only for go clean, go run or go build works fine.

Here is the folder structure of main code:

.
├── Makefile
├── cmd
│   └── server
│       └── main.go
├── go.mod
├── go.sum
└── pkg
    └── storage
        └── mysql
            └── storage.go

Here is how the go.mod file looks like:

module github.com/marvincaspar/go-example
go 1.12

require (
    github.com/go-sql-driver/mysql v1.4.1
)

And finally the main.go file:

package main

import (
    "fmt"
    "os"

    "github.com/marvincaspar/go-example/pkg/storage/mysql"
)

func main() {
    if err := run(); err != nil {
        fmt.Fprintf(os.Stderr, "%v", err)
        os.Exit(1)
    }
}

func run() error {
    // init storage
    s := mysql.NewStorage()
    // do some other stuff...
}

Any ideas what I am doing wrong?

  • 写回答

1条回答 默认 最新

  • drsw9390405 2019-04-11 12:32
    关注

    Go build/install is trying to find main package in your root directory, it is not checking sub-directories (cmd/server) in your case. Hence you are getting package not found error.

    To properly build your code, you can run:

    go build github.com/marvincaspar/go-example/cmd/server
    

    Similarly, to run your project, you will have to provide module-name/main-package-path:

    go run github.com/marvincaspar/go-example/cmd/server
    

    Go clean can be executed in same way, by providing module-name/path-with-main-package

    go clean github.com/marvincaspar/go-example/cmd/server
    

    or

    GOPATH="$(pwd)/vendor:$(pwd)" GOBIN="$(pwd)/bin" go clean github.com/marvincaspar/go-example/cmd/server 
    

    However, as per https://blog.learngoprogramming.com/code-organization-tips-with-packages-d30de0d11f46, just put your source files into your project’s root. It’s better that way.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏