In this chapter, we are looking at downloading and using external modules.
This chapter will cover:
- Creating a project.
- Adding an external module to your project.
- Use the external library in your app.
To consume an external module, you need to:
- Import it, involves using the
import
instruction and fully qualifying the address to the module's location. - Use it in code, call the code from the module that you mean to use
- Ensure it's downloaded, so your code can be run.
To import a module, you can do one of two things:
go get <path to module>
, this will fetch the module and download it and make it available for your project to use.go mod tidy
, this command checks the imports used in your program and fetches the module if not fetched already.
To use your module in code, you need to add it to the import
section and then invoke it where you need it in the application code.
import (
"github.com/<user>/<repo name>"
)
func main() {
<repo name>.<Function>()
}
Here's an example:
package main
import (
"fmt"
"github.com/softchris/math"
)
func main() {
math.Add(1,1) // 2
}
Let's create a new project
-
Run
go mod init
:go mod init hello
Note how go.mod was created with the following content:
module hello go 1.16
Next, lets create some code that will use the external library:
-
Create the file main.go
package main import ( "fmt" "github.com/softchris/math" )
-
To the same file, add a
main()
function and call the externalAdd
method from themath
package:func main() { sum := math.Add(1,2) fmt.Println(sum) }
Now, we need to resolve the external library.
-
Run
go mod tidy
:go mod tidy
Your go.mod is updated:
require github.com/softchris/math v0.2.0
There's also go.sum file with the following content:
github.com/softchris/math v0.2.0 h1:88L6PLRBGygS3LY5KGIJhyw9IZturmd2ksU+p13OPa4= github.com/softchris/math v0.2.0/go.mod h1:v8WzhjKC+ipuH+i9IZ0Ta2IArniTP53gc5TgCINCqAo=
This is Go's way of keeping track of how to build the app by referencing to the go module in question.
-
Run
go run
:go run main.go
Running the program gives you the following output:
3
go.sum
github.com/softchris/math v0.2.0 h1:88L6PLRBGygS3LY5KGIJhyw9IZturmd2ksU+p13OPa4=
github.com/softchris/math v0.2.0/go.mod h1:v8WzhjKC+ipuH+i9IZ0Ta2IArniTP53gc5TgCINCqAo=
go.mod
module hello
go 1.16
require github.com/softchris/math v0.2.0
main.go
package main
import (
"fmt"
"github.com/softchris/math"
)
func main() {
sum := math.Add(1,2)
fmt.Println(sum)
}
See if you can find another module you want to use in your project. Add it to the project and use it in your code.