Programming in GO is quick and fun. You can write a working, compiled application with a few lines of code. In this example, we will use Visual Studio Code to edit the source code, and we have already configured it to start from the command line with the “code” command.
Write your first Go application
Create a directory for your application, let’s call it myapp
mkdir myapp
Open a terminal window in the myapp directory
cd myapp
Initialize the Go Modules. Go modules are available since Go version 1.11, in Go version 1.13 is the default over $GOPATH. In the main directory of your application execute
go mod init github.com/MY_USER_NAME/myapp
When we add an import statement to the code, Go will automatically update the go.mod file to include the dependency with the latest stable version. To list the referenced modules execute
go list -m all
Create a file for your module. This file is not required, but as it is on the top level, the package name is considered to be the name of the module.
code config.go
Enter to code
package myapp
func Config() string {
return "Application config"
}
Create a sub-directory for the entry point of your application. When someone imports your application as a module this will be the command to execute.
mkdir -p cmd/myapp
Create the file for the command
code cmd/myapp/myapp.go
Create the main function
package main
import (
"fmt"
"github.com/MY_USER_NAME/myapp"
)
func main() {
fmt.Println(myapp.Config())
}
Save the files and run the application
go run cmd/myapp/*
The output should be
Application config
Add a package to the application
mkdir mypackage
Create the package file
code mypackage/mypackage.go
Write the code of the package
package mypackage
func RunMyPackage() string {
return "MyPackage running"
}
Update the main function to call the new package
code cmd/myapp/myapp.go
Add two lines to the code
package main
import (
"fmt"
"github.com/MY_USER_NAME/myapp"
"github.com/MY_USER_NAME/myapp/mypackage" // NEW LINE
)
func main() {
fmt.Println(myapp.Config())
fmt.Println(mypackage.RunMyPackage()) // NEW LINE
}
Save the files and run the application. The output should be
go run cmd/myapp/*
Application config
MyPackage running
Using modules from other applications
To upgrade a module to the latest tagged version for example golang.org/x/text
go get golang.org/x/text
List all available versions of a module, for example, rsc.io/sampler
go list -m -versions rsc.io/sampler
Get a specific version of the module
go get rsc.io/sampler@v1.3.1
To remove unused dependencies from the go.mod and go.sum file
go mod tidy