Search code examples
gosharedgo-modules

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?


Solution

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