Search code examples
gogo-modules

Referencing a Go module that is local


I've been unsuccessful in importing a package from a local project (a Go module). Here is a brief of what I'm trying:

I created a Go module package like so:

  $ cd 
  $ mkdir mymodule
  $ cd mymodule
  $ go mod init github.com/Company/mymodule

Then I added hello.go under the mymodule with a little function

// mymodule/hello.go

package mymodule

func sayHello() string {
    return "Hello"
}

go build was successful.

Note that the module is not pushed to github repository yet. I want to use (and perhaps test) mymodule before I push to github. So I created another package, like so:

  $ cd 
  $ mkdir test
  $ cd test
  $ go mod init github.com/Company/test

Then, created a new file test.go under the test directory and in there I try to import mymodule, like so:

// test/test.go

import (
    "fmt"
    "github.com/Company/mymodule"
)

func testMyModule() {
    fmt.Println(mymodule.sayHello())
}

But go build of test fails with the below error. What gives?

cannot load github.com/Company/mymodule: cannot find module providing package github.com/Company/mymodule

Solution

  • When resolving dependencies in your go.mod, Go will try to resolve the third-party modules by fetching them from the remote URL that you've provided.

    The remote URL, unless you've pushed it to GitHub for example, doesn't exist. This is when you get an error like this:

    cannot load github.com/Company/mymodule: cannot find module providing package github.com/Company/mymodule
    

    There is a work-around for local modules, you can use the replace keyword in your go.mod file.

    replace github.com/Company/mymodule v0.0.0 => ../mymodule
    

    This will let Go know where to find your local dependency. Just make sure to use the correct relative path to your module.

    Once your local tests are complete and you've pushed your module to a repository, then you can remove the replace line from your go.mod and use

    go get -u github.com/Company/mymodule`
    

    to get the module correctly working alongside your current project.

    As a side note, functions and variables in Go packages should start with a capital letter to be accessible from outside the package itself.

    Good luck!