golang: How to manage packages in the local file-system

Viewed 38

i am sure this has been asked many, many times: »How can i create and manage my go-packages locally without for example github ?«

I need to convert a couple of tools that were written in Perl to golang and i am fighting with golang's package management, simple example:

I wrote the main-package, containing the main function and a couple of other functions. Now i want to move a group of functions into another package:

  • Created another package in the same directory and moved the group of functions there
  • Built the package and the binary-file was created
  • Tried to import this package into the main package and miserably failed. "PackageName", "./PackageName" "[fullpath]/PackageName" all fails

For starters: How can i import a package from the local file-system?

1 Answers

Run go mod init <module_name> in the dir where you want to store all your code.

Example: go mod init auth-api

This will create a go.mod file in your root folder.

You can create a separate folder for each package.

Your dir structure looks like this.

package_1
-- file_1_1.go
-- file_1_2.go
package_2
-- file_2_1.go
-- file_2_2.go
-- file_2_3.go

main.go
go.mod

Here package_1 contains the file_1_1.go and file_1_2.go. Start these files with package package_1

Ex:

// file_1_1.go

package package_1
import "fmt"

func SayHelloFromPackage_1(){
   fmt.Println("Hello from Package 1")
}

Now you can use that function in main.go:

// main.go
import "auth-api/package_1" // auth-api is our module name (go mod init auth-api)

func main() {
    package_1.SayHelloFromPackage_1()
}

Related