LoginSignup
20
13

More than 3 years have passed since last update.

【Golang】Go 1.14での独自パッケージimportでエラーになるとき

Posted at

数年Goを離れてたら、バージョン1.14になってたのでキャッチアップしなければ(Go 1.10の人)。
go modによる管理が楽しい。

TL;DR

  • 各ディレクトリにgo.modを設置
    • go mod initをする
  • local importするため各go.modファイルにreplaceを追加
    • 参照階層がネストするときに注意
      • 例)main.go → ./api.go → ./domain/models/Sample.go
      • mainのgo.modにはreplace文が2行必要になります
        • main.goから見たapiの相対パス
        • main.goから見たmodelsの相対パス

出てきて困ったエラー

C:\Users\username\go\src\github.com\username\repo>go build ./...
go: finding module for package github.com/username/repo/domain/models
api\api.go:13:2: no matching versions for query "latest"

とか

go: github.com/username/repo/api@v0.0.0-00010101000000-000000000000 requires
        github.com/username/repo/domain/models@v0.0.0-00010101000000-000000000000: invalid version: unknown revision 000000000000

前提

go envの結果です。

env.log
set GO111MODULE=on
set GOPATH=C:\Users\username\go

ディレクトリ構成

%GOPATH%配下である必要はないですが、一応標準的な配置。本記事に関係ないファイルを除外して記載してあります。

tree.log
%GOPATH%\src\github.com\username\repo
│  main.go
│
├─api
│      api.go
│
└─domain
   └─models
          Sample.go

解決手順

./main.go→./api/api.go

main.goのなかで、自作apiパッケージを利用する場合、下記の手順が必要。

  • main.goと同階層にあるgo.modにreplace追加
    • replace github.com/username/repo/api => ./api
  • apiの階層にgo.mod作成
    • cd ./api
    • go mod init
  • main.goにimport
    • import api "github.com/username/repo/api"

./api/api.go→./domain/models/Sample.go

api.goのなかで、自作modelsパッケージを利用する場合、下記の手順が必要。

  • api.goと同階層にあるgo.modにreplace追加
    • replace github.com/username/repo/domain/models => ../domain/models
    • そのgo.modから見ての相対パスなので注意!
  • domain/modelsの階層にgo.mod作成
    • cd ./domain/models
    • go mod init
  • api.goにimport
    • import models "github.com/username/repo/domain/models"
  • main.goと同階層にあるgo.modにもreplace追加
    • replace github.com/username/repo/domain/models => ./domain/models

mainのgo.mod

go.mod
module github.com/username/repo

go 1.14

replace (
    github.com/username/repo/api => ./api
    github.com/username/repo/domain/models => ./domain/models
)

require (
    ...
)

apiのgo.mod

go.mod
module github.com/username/repo/api

go 1.14

replace github.com/username/repo/domain/models => ../domain/models

require (
    ...
)

解決後のgo.mod分布イメージ

tree.log
%GOPATH%\src\github.com\username\repo
│  go.mod
│  go.sum
│  main.go
│
├─api
│      api.go
│      go.mod
│      go.sum
│
└─domain
   └─models
          go.mod
          Sample.go

今回は問題なかったけど

  • 将来domain直下に.goファイルが出てくるようになったら、今回と同様の手順で解決できるはず
  • domain/repositoriesとか作ってrepositoriesパッケージ使う場合も同じお話

同ジャンルのQiitaの先人たち

20
13
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
13