Golang
Tags: go
Published: 2019-11-14 15:46:15

#Part 1

**Introduction**
<strong>G</strong>olang also known as `GO` is an open source computer programming language created by Google, it was developed at Google in 2007 by *Robert Griesemer*, *Rob Pike* and *Ken Thompson*, and was officially released and introduced to the public in 2009.
![Golang Developers](https://pbs.twimg.com/media/CnPK1TtWgAQTDOn?format=jpg&name=small)
<figcaption>From the left: Robert Griesemer, Rob Pike and Ken Thompson</figcaption>
**What Is Golang**
Golang is a general purpose programming language, making it useful in a wide range of areas, varying from web apps, network servers, mobile apps and machine learning, just to mention a few.
Golang is a statically typed and compiled programming language like the C family.
```golang
package main

import (
	"fmt"
)

func main() {
	fmt.Println("Hello, playground")
}
```
```golang
//Result
Hello, playground
```
[<figcaption>Run in Playground<figcaption>](https://play.golang.org/p/HmnNoBf0p1z)
Golang comes with some amazing features like memory safety, garbage collection, structural typing and concurrency, which I would go through as we move further in this article.
However the Golang programming language is engineered for building larger scale and complex software, projects that involves distributed networks, cloud services and other backend technologies, it can also be very useful in solving problems encountered in complex software infrastructure as you scale.

**Some Major Features Of Golang**
* Compiled Programming Language: Golang generates binaries for your applications, complete with dependencies, no iinterpreters or run-time installations are required. In simple terms Golang generates machine code directly from the source code and not from interpreters, in this case no pre-runtime translation takes place, making it a very fast programming language.
![Golang Image](https://blog.charmes.net/images/gopherswrench.jpg) 
* Error Handling: Golang is a statically typed programming language, that supports type safety, errors are caught by the compiler before execution.
Go codifies errors with the built-in error interface:
```golang
type error interface {
    Error() string
}
```
```golang
//Result
can't load package: package main: 
prog.go:1:1: expected 'package', found 'type'
```
[<figcaption>Run in Playgroung</figcaption>](https://play.golang.org/p/YogGzKzN1L9)

Error values are used just like any other value.

```golang
func doSomething() error

err := doSomething()
if err != nil {
    log.Println("An error occurred:", err)
}  
```
```golang
//Result
can't load package: package main: 
prog.go:1:1: expected 'package', found 'func'
```
[<figcaption>Run in Playground</figcaption>](https://play.golang.org/p/LEm3iCakR2p)
* Garbage collection: This is one of the exciting features of Golang, havr you ever thought of how messages are pushed in real-time that fast? Low latency garbage collection plays an important role in this.
In simple terms garbage collection is the process of freeing memory space that is not being used, this process happens in a concurrent way while the program is running and not before or after execution of the program. Concurrency would be explained as we go further into the article.
Read more on implementing memory management with Golang’s garbage collector [here](https://hub.packtpub.com/implementing-memory-management-with-golang-garbage-collector/)
* Multi-Paradigm: Golang supports multiple programming paradigms including, Object Oriented Programming(OOP) without inheritance and functional programming.
![Golang Image](https://talks.golang.org/2012/waza/gophercomplex1.jpg)
* Concurrency: Basically this is simply the ability of the program to do multiple things at the same time, which allows it to handle numerous task at once in a given period of time. Golang has a very good support for concurrency using goroutines and channels.
* Goroutines: A goroutine is a function or method that is capable of running concurrently with other functions or methods.
```golang
package main

import (
	"fmt"
	"time"
)

func print() {
	fmt.Println("Printing from goroutine")
}

func main() {
	go print()
	time.Sleep(1 * time.Second)
	fmt.Println("Printing from main")
}
```
```golang
//Result
Printing from goroutine
Printing from main
```
[<figcaption>Run in Playground</figcaption>](https://play.golang.org/p/uIADiGYg1J-)

From the code snippet above, we have a function print which is just printing a string, in the main function, we have called this function concurrently by using  `go` as a prefix. So now we have 2 goroutines, first our main function and second our print function. We made the main goroutine to sleep for 1 second so that `go print()` has enough time to execute before the main groutine terminates, then the program will be terminated and no goroutine will run.
You can try this program by commenting  `go print()`.

```golang
//Result
Printing from main
```
[<figcaption>Run in Playground</figcaption>](https://play.golang.org/p/okJQ4epTQpx)

* Channels: In the goroutine code snippet above we used time.sleep to see the difference between how goroutine works, however a better way to do this is by using channels, goroutine actually communicates with each other by channels.
```golang
package main

import (
	"fmt"
)

func print(ch chan bool) {
	fmt.Println("Printing from goroutine")
	ch <- true
}

func main() {
	ch := make(chan bool)
	go print(ch)
	<-ch
	fmt.Println("Printing from main")
}
```
```golang
//Result
Printing from goroutine
Printing from main
```
[<figcaption> Run on Playground</figcaption>](https://play.golang.org/p/zcaqlFu8emv)

From the code snippet above, we defined a channel ch on line 13 and on line 14 we call print goroutine passing channel as argument. Our print function receives this channels, prints the `Printing from goroutine` and writes true to the channel. When this write is complete, the main goroutine receives the data from the ch channel, till this time our main goroutine was blocked and once it read data from the channel ch, it is unblocked and then the text `Printing from main` is printed.
Read more about concurrency [here](http://www.golangbootcamp.com/book/concurrency)

> Note: Concurrency is a property of a program where two or more tasks can be in progress simultaneously. Parallelism is a run-time property where two or more tasks are being executed simultaneously. Through concurrency you want to define a proper structure to your program. Concurrency can use parallelism for getting its job done but remember parallelism is not the ultimate goal of concurrency.

> *Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once.* — Rob Pike

**Some Drawbacks Of Golang:**
* Less Flexibility: Golang has less flexibility than in dynamically typed languages, static typed programming languages like Golang types are checked before runtime while dynamic typed programming languages like JavaSript are checked on the fly during execution.
```golang
package main

import (
    "fmt"
)

func main() {
    m := "6"
    n := 6

    fmt.Println(m + n)
}
```
```golang
//Result
./prog.go:11:19: invalid operation: m + n (mismatched types string and int)
```
[<figcaption>Run in Playground</figcaption>](https://play.golang.org/p/lSenzovs8b7)

In the code snippet above, statically typed languages like Golang would throw an error because they don't allow for type coercion.
```javascript
function main(){
  var m = "6";
  var n = 6;
  
  console.log(m + n);
}

main();
```
```javascript
//Result
66
```
[<figcaption>Run in Sandbox</figcaption>](https://codesandbox.io/s/distracted-grass-42291?fontsize=14&hidenavigation=1&theme=dark)
In the  code snippet above, dynamically typed languages like JavaSript would merge the string and the number together.

* Smaller Number Of Packages: As compared to other ecosystem like Node.js. This is because Golang's standard is full of features which mostly doesn't need third-party support. However, the number of packages are increasing.

In conclusion here are some real world examples of tools and software that uses Golang:
* Kubernates: The Google-backed container platform.
* Drop-box: The cloud storage and file sharing.
* Cloudfare: A content delivery network, DDoS mitigation ans internet security service.
* Malware bytes: An antivirus software.

# Part 2
### Installation
![Windows](https://marcofranssen.nl/images/951957866431d77793480aba8bb624da2f6b3fb2.gif)
#### Installation Of Golang on Windows OS:
* You’ll be completing most of the installation and setup on a command-line interface, which is a non-graphical way to interact with your computer. Make sure  you have an internet connection and administrative access.
```git
cd ..
```
Switch to your home directory, for example `C:\Users\kenny`
* Navigate to the Go installation website [here](https://golang.org/doc/install). Download and install the latest 64-bit Go set for Microsoft Windows OS.
* After the installation, run the Command Prompt on your computer `go version`.
You should see something similar to this on your command prompt:
```git
Microsoft Windows [Version 10.0.16299.15]
(c) 2017 Microsoft Corporation. All rights reserved.
c:\Users\kenny>go version
go version go1.10 windows/amd64
```
* Create your work-space, confirm your Go binaries by 
going to your computer’s Control Panel, then to `System and Security > System > Advanced system settings`, and on the left-hand pane click the Advanced tab. Then click on Environmental Variables on the bottom-right-hand side. Ensure Path under System Variables has the “C:\Go\bin” variable in it.
Then create your Go work-space. This will be in a separate and new folder from where the Go installation files are saved. For example, your G installation files were saved under the path `C:\Go` and you are creating your Go work-space under `C:\Projects\Go`
In your new Go work-space folder, set up three new folders:

![Folder Creation](https://cdn-media-1.freecodecamp.org/images/1*I3BO4S6FQ6keH6o75ATuBg.png)

* Create the GOPATH variable and reference your newly-created Go work-space. Go back to your Control Panel and navigate to System and then Environmental Variables. Then under System Variables click on New.
Next to Variable Name, enter `GOPATH,` and next to Variable Value enter `C:\Projects\Go`.
![File path](https://cdn-media-1.freecodecamp.org/images/1*EdndcOEfhY8DWreAWXjung.png)
```git
Microsoft Windows [Version 10.0.16299.15]
(c) 2017 Microsoft Corporation. All rights reserved.
c:\Users\kenny>echo %GOPATH%
```
<figcaption>Check that your path has been set correctly, by entering "echo %GOPATH%" on the command line.</figcaption>

* Verify that all is working correctly by opening the command line and typing: `go get github.com/golang/example/hello`
Wait for the code to be entirely implemented (this could take a few seconds), then enter in the following in the command line: `%GOPATH%/bin/hello`
If the installation was successful, you should get the following return message: `Hello, Go examples!`.
```git
c:Users\kenny>go get github.com/golang/example/hello
c:Users\kenny>%GOPATH%/bin/hello
Hello, Go examples!
c:\Users\kenny>
```
I hope the installation was successful. And if you run into any errors or confusing messages. You can reference [here](http://www.wadewegner.com/2014/12/easy-go-programming-setup-for-windows/).
Congrats you are now ready to develop in Golang.

#### Installation Of Golang on a Mac OS:
* To download the latest Go release visit [here](https://golang.org/dl/). You will see the download link for Apple macOS. The current version of Go 1.13 support macOS 10.10 or later versions with 64-bit support only.
Alternatively, you can download Go 1.13.3 using the curl command line.
```iterm
$ curl -o golang.pkg https://dl.google.com/go/go1.13.3.darwin-amd64.pkg
```
* You have downloaded the Go package on your macOS system. To install it simply double click on the downloaded file to start the installation wizard.
Command-line users can execute the below command to start the installation. 
```iterm
$ sudo open golang.pkg
```
Follow the installation wizard and complete the installation process.
* Edit the `~/.bash_profile` or `~/.profile` file (or its equivalent) to set environment variables. Commonly you need to set 3 environment variables as `GOROOT`, `GOPATH` and `PATH`.
`GOROOT` is the location where Go package is installed on your system.
```iterm
$ export GOROOT=/usr/local/go
```
`GOPATH` is the location of your work directory. For example my project directory is `~/Projects/Proj1`.
```iterm
$ export GOPATH=$HOME/Projects/Proj1
```
Now set the `PATH` variable to access go binary system wide.
```iterm
$ export PATH=$GOPATH/bin:$GOROOT/bin:$PATH
```
* The `govendor` is a tool used for managing the Go application dependencies efficiently. You should consider this to install on your system.
```iterm
go get -u github.com/kardianos/govendor
```
* Finally, you have successfully installed and configured go language on your system. First, use the following command to check the installed Go version.
```iterm
$ go version

go version go1.13.3 darwin/amd64
```
I hope the installation was successful. And if you run into any errors or confusing messages. You can reference [here](https://medium.com/golang-learn/quick-go-setup-guide-on-mac-os-x-956b327222b8).
Congrats you are now ready to develop in Golang.

#### Installation Of Golang on Linux OS:
* Go [here](https://golang.org/dl/) and download the latest version of GoLang in an archive file as follows:
```iterm
$ cd ~/Downloads
$ wget -c https://storage.googleapis.com/golang/go1.7.3.linux-amd64.tar.gz
```
* Next, check the integrity of the tarball by verifying the SHA256 checksum of the archive file [here](https://www.tecmint.com/generate-verify-check-files-md5-checksum-linux/) using the shasum command as below, where the flag `-a` is used to specify the algorithm to be used:
```iterm
$ shasum -a 256 go1.7.3.linux-amd64.tar.gz

ead40e884ad4d6512bcf7b3c7420dd7fa4a96140  go1.7.3.linux-amd64.tar.gz
```
To show that the contents of the downloaded archive file are the exact copy provided on the GoLang website, the 256-bit hash value generated from the command above as seen in the output should be the same as that provided along with the download link.

If that is the case, proceed to the next step, otherwise download a new tarball and run the check again.
* Then extract the tar archive files into `/usr/local` directory using the command below.
```iterm
$ sudo tar -C /usr/local -xvzf go1.7.3.linux-amd64.tar.gz
```
Where, `-C` specifies the destination directory..
Configure your environment,  first, setup your Go workspace by creating a directory `~/go_projects` which is the root of your workspace. The workspace is made of three directories namely:
 * `bin` which will contain Go executable binaries.
 * `src` which will store your source files and
 * `pkg` which will store package objects.
Therefore create the above directory tree as follows:
```iterm
$ mkdir -p ~/go_projects/{bin,src,pkg}
$ cd ~/go_projects
$ ls
```
* Now it’s time to execute Go like the rest of Linux programs without specifying its absolute path, its installation directory must be stored as one of the values of [$PATH environment variable.](https://www.tecmint.com/set-path-variable-linux-permanently/)
Now, add `/usr/local/go/bin` to the `PATH` environment variable by inserting the line below in your `/etc/profile` file for a system-wide installation or `$HOME/.profile` or `$HOME./bash_profile` for user specific installation:
Using your preferred editor, open the appropriate user profile file as per your distribution and add the line below, save the file and exit:
```iterm
export  PATH=$PATH:/usr/local/go/bin
```
* Then, set the values of `GOPATH` and `GOBIN` Go environment variables in your user profile file (`~/.profile` or `~/bash_profile`) to point to your workspace directory.
```iterm
export GOPATH="$HOME/go_projects"
export GOBIN="$GOPATH/bin"
```
>Note: If you installed GoLang in a custom directory other than the default (`/usr/local/`), you must specify that directory as the value of `GOROOT` variable.
For instance, if you have installed GoLang in home directory, add the lines below to your `$HOME/.profile` or `$HOME/.bash_profile` file.
```iterm
export GOROOT=$HOME/go
export PATH=$PATH:$GOROOT/bin
```
* The final step under this section is to effect the changes made to the user profile in the current bash session like so:
```iterm
$ source ~/.bash_profile
```
OR
```iterm
$ source ~/.profile
```
* Finally time to verify the installation, Run the commands below to view your Go version and environment:
```iterm
$ go version
$ go env
```
* To test your if your Go installation is working correctly, write a small Go hello world program, save the file in `~/go_projects/src/hello/` directory. All your GoLang source files must end with the `.go` extension.
Begin by creating the hello project directory under `~/go_projects/src/`:
```iterm
$ mkdir -p ~/go_projects/src/hello
```
Then use your favorite editor to create the `hello.go` file:
```iterm
$ vi ~/go_projects/src/hello/hello.go
```
Add the lines below in the file, save it and exit:
```iterm
package main 

import "fmt"

func main() {
    fmt.Printf("Hello, you have successfully installed GoLang in Linux\n")
}
```
* Now, compile the program above as using go install and run it:
```iterm
$ go install $GOPATH/src/hello/hello.go
$ $GOBIN/hello
```
* To run your Go binary executables like other Linux commands, add `$GOBIN` to your `$PATH` environment variable.
I hope the installation was successful. 
And if you run into any errors or confusing messages. You can reference [here](https://www.ostechnix.com/install-go-language-linux/).
Congrats you are now ready to develop in Golang.

![Go image](https://cdn-media-1.freecodecamp.org/images/1*z6i4jwGkvPE3S21x_PmvMw.png)