Help us understand the problem. What is going on with this article?

【Go言語】作成したpackageをimportして使用。「cannot find module for path」エラー時の解決

◇ 流れ

【Go言語】packageを作成

importに「./XXXXX」でパス指定

実行

「cannot find module for path」と怒られる

解決

◇ ディレクトリ構成

:file_folder: GOPATH
 ┣━ :file_folder: bin
 ┣━ :file_folder: pkg
 ┗━ :file_folder: src
    ┗━ :file_folder: test
       ┣━ :file_folder: route
       ┃   ┗━ :page_facing_up: route.go
       ┣━ :page_facing_up: go.mod
       ┗━ :page_facing_up: main.go

◇ go環境

ターミナル
$ go version
go version go1.13.4 windows/amd64

$ go env
set GO111MODULE=on
set GOBIN=C:\GOPATH\bin
set GOENV=C:\Users\XXXXXX\AppData\Roaming\go\env
set GOEXE=.exe
set GOHOSTARCH=amd64
set GOOS=windows
set GOPATH=C:\GOPATH
set GOROOT=C:\Go

◇ go.mod を作成。

プロジェクトルートに、$ go mod initgo.modを作成。

ターミナル
$ cd C:\GOPATH\src\test

$ go mod init
go: creating new go.mod: module test
go.mod
module test

go 1.13

◇ main.go と route パッケージを作成。

main.go
package main

import "./route"

func main() {
    route.Route()
}
route/route.go
package route

import (
    "github.com/labstack/echo"
    "net/http"
)

func Route() {
    e := echo.New()

    e.GET("/", getHandler)

    e.Logger.Fatal(e.Start(":1323"))
}

// サイトを表示させる
func getHandler(c echo.Context) error {
    return c.String(http.StatusOK, "Hello, World!")
}

◇ 実行

ターミナル
go run main.go
go: finding golang.org/x/crypto latest
build _/c_/GOPATH/src/test/route: cannot find module for path _/c_/GOPATH/src/test/route

cannot find module for pathとエラーがでて怒られた。。。

パスはあっているのに何故か、
package の読み込みが出来ていないのでかなり詰まりました。

↓↓↓↓↓ 解決策 ↓↓↓↓↓↓

go.modにmodulの名前があるので
「./route」を「test/route」に置き換える

go.mod
module test ← modulの名前

go 1.13
main.go
package main

import "./route" → "test/route"  に変更

func main() {
    route.Route()
}

参考サイト

go 1.11のmodules(vgo)が有効な環境で相対importが cannot find module for path でエラーになった話。
https://pod.hatenablog.com/entry/2018/12/26/074944

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした