Creating a Go Package

Some quick instructions on how to create a package and a module in Go (GoLang).

Your directory of files will look like this.

example/
  main.go
  special/
    thing.go

Your code will look like this.

main.go

package main

import "example/special"

func main() {
	special.Thing()
}

special/thing.go

package special

func Thing() {
	println("Special Thing")
}

Online Packages

If you call your package something like joeldare.com/example instead of example then you can put the package files online and it can be loaded from that URL instead of the local directory. To do that you would change the init command to something like go mod init joeldare.com/example. In that case, your main.go might look like this.

package main

import "joeldare.com/example/special"

func main() {
	special.Thing()
}

It will still load the special package from the special/ directory if it’s there but if not it will look for it online at joeldare.com/example/special.


Joel's Newsletter

Get a monthly digest of what I'm up to.

Subscribe by Email