This is a quick tutorial on getting started with Golang. In this tutorial, we will see how to build a simple Hello World go app step by step.
Check out 50+ Golang source code examples at https://www.sourcecodeexamples.net/p/golang-source-code-examples.html
Installation
We can go to https://golang.org/dl/ and download the binary depending on our Operating System and install it. Once installed run go version and you should be able to see the go version.
$ go versiongo version go1.14.1 darwin/amd64$
Once go is installed set GOPATH environment variable. On MacOS by default, it is set to ${user.home}/go. We can also add $GOPATH/bin to our PATH.
$export GOPATH=~/go$export PATH=$PATH:$GOPATH/bin
Quickstart
Create New Project
Create a new project directory hello-go and cd into the directory:
$ mkdir hello-go&cd hello-go
In the hello-go directory create hello.go file with the following content:
hello.go
package mainimport"fmt"funcmain() {fmt.Println("Hello World!!!")}
Now you can run the application using go run hello.go and build the application as executable binary using go build as follows:
hello-go> go run hello.goHello World!!!hello-go> go buildhello-go> lshello hello.gohello-go> ./helloHello World!!!
We can install 3rd-party dependencies using go get command as follows:
hello-go> go get -u github.com/mitchellh/go-homedirhello-go> cat go.modmodule github.com/sivaprasadreddy/hello-gogo 1.14require github.com/mitchellh/go-homedir v1.1.0 // indirecthello-go>
We can use homedir module as follows:
hello.go
package mainimport ("fmt""github.com/mitchellh/go-homedir""os")funcmain() {fmt.Println("Hello World!!!")home,err:=homedir.Dir()iferr!=nil {fmt.Println("Error: ",err)os.Exit(1)}fmt.Println("My Home directory: ",home)}
Comments
Post a Comment