Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use internal packages with go modules?

I am using go modules in my project. I have shared code in the internal folder.

.
├── README.md
├── internal
│   └── shared
│       ├── request.go
│       └── request_test.go
└── web
    ├── README.md
    └── go
        └── src
            └── webservice
                ├── go.mod
                ├── go.sum
                └── main.go

I am not able to access the internal/shared from webservice while using go modules. I get the following error:

package internal/shared is not in GOROOT (/usr/local/go/src/internal/shared)

While importing from webservice in main.go:

import "internal/shared"

Note: I am trying to share internal/shared with another mod that is not listed above.

How to fix this issue?

like image 338
ssk Avatar asked Apr 20 '20 17:04

ssk


3 Answers

Your go.mod inside web/go/src/webservice indicates that this package is located in a different module than your internal/shared package. It should work when you move your go.mod and go.sum at the root of the whole project. Then the web/go/src/webservice and internal/shared packages will be inside one go module.

This worked for me:

    .
    ├── go.mod
    ├── go.sum
    ├── internal
    │   └── shared
    │       └── request.go
    │  
    └── web
        └── go
            └── src
                └── webservice
                    └── main.go

And you should include the whole go-module path when importing the internal/shared package in your main.go.

So, inside your main.go the import should look like import "$your-go-module/internal/shared"

More info on internal packages here

like image 68
fabem Avatar answered Nov 06 '22 20:11

fabem


I ended up fixing by adding a go.mod to the internal/shared and editing the go.mod in webservice with the following:

module webservice

go 1.14

replace example.com/shared => ../../../../internal/shared/

require (
    github.com/gorilla/mux v1.7.4
    github.com/spf13/viper v1.6.3
    github.com/stretchr/testify v1.5.1
    example.com/shared v0.0.0-00010101000000-000000000000
)

example.com/shared v0.0.0-00010101000000-000000000000 was generated by "go mod init webservice"

like image 3
ssk Avatar answered Nov 06 '22 21:11

ssk


In my case, the code was compiling fine, but the GoLand IDE was unable to recognise the imports. The issue was exactly as described here.

I'm using go modules and a directory outside of the GOPATH. External dependencies are recognized just fine, packages inside my projects "cannot be found" by GoLand.

The fix is to tick the checkbox for Enable Go Modules (vgo) integration under Settings/Preference -> Go -> Go Modules (vgo).

Here is the screenshot for the same.

enter image description here

like image 1
Sumit Jha Avatar answered Nov 06 '22 19:11

Sumit Jha