System ProgrammingIncrease Productivity with Golang Programming

Increase Productivity with Golang Programming

In this article we will demonstrate how Golang and Docker can boost productivity with rapid application development. Go has a syntax similar to the C family of languages and with its lightweight type system and built-in concurrency provides performance comparable to C while offering super-fast compile time for large projects. Like Java, Go is statically typed and garbage-collected, however unlike Java, Go is natively or AOT-compiled.

Application Design Considerations for GoLang

Go is ideal for building cloud applications, distributed and concurrent applications and for system programming. Go or Golang was designed by Google to circumvent issues they were facing with C/C++. Google also wanted Go too critically to obtain the smallest possible compile time so that it would compete in productivity terms with dynamic scripting languages such as Python or Ruby for rapid application development. They were happy to lose language features from C++ if the essential compile time boost increased productivity and performance. As an example of this is Go does not directly support inheritance in its type system rather it supports composition.

Unlike the Java Virtual Machine the Go runtime is a Go package. Go programs are compiled into machine code by the Go toolchain. Since Go provides high level constructs such as goroutines (equivalent to lightweight threads), channels (pipes for goroutines) and garbage collection, the runtime implemented to support these features is optimised for concurrency. Currently this runtime is implemented in C and statically linked to the compiled application code during linking. As a consequence a Go application appears as a standalone executable to the operating system and can be conveniently packaged with Docker. When creating Go code you work with the system library, the runtime magically supports your application code.

A core goal of the Go design was to enable concurrency as a fundamental construct of the language. This is achieved in many ways, such as goroutines, however the Go runtime plays an important role managing interaction of the codes spawned threads which you need to understand, the key fact is the goroutines still share threads. To manage this the Go runtime has a scheduler which implements a cooperative multitasking scheme. Any calls that the Go application makes to the underlying system are intercepted by the Go runtime. Effectively this means that the Go runtime will spawn a new thread when needed to prevent blocking on system calls.

If you are new to Go and concurrent application development all this reduces down to a simple fact when you compile and link to your executable the binary is much larger than you would expect. This is because the included runtime has all this runtime power embedded to magically allow your application to perform concurrent tasks to fully maximise the number of available CPU cores provided by the system.

If you were to do this in Java then your runtime is the Java Virtual Machine and you will need to go through the often painful experience of packaging a java runtime into your deliverable executable. If you were to do this in Python then your runtime is the Python interpreter. If you were to create an equivalent C binary then you would need to link in all the equivalent resources in your makefile.

Set Up a Go Development Environment with Docker.

A quick way to get up and running with Go is to use Docker. There is the official image at DockerHub however to illustrate the principles we will build our own image that will allow us to easily drive Go from a bash terminal. Then if you are new to Docker and Go using the understanding gained will make the official image more accessible.

The source code can be found here. When you build the Dockerfile we set up a debian system with Go correctly installed and a bash terminal with the following Environment and Path variables configured.

1. Go SDK
2. GOPATH

The Go SDK is just the bin directory of whether you have installed the Go binaries, in this case
/usr/local/go/bin. This needs to be appended to the Path variable.
The GOPATH variable is the path to the location of where you are developing your Go code.

The following lines in the Dockerfile show this

ENV PATH /gopath/bin:/usr/local/go/bin:$PATH
ENV GOPATH /gopath

We will develop the code in the main directory below

WORKDIR /gopath/src/main

In the same directory as the Dockerfile issue the following command to build the image.

docker build -t="eduonix/golangtools:1.0.0" .

The first time it builds can take a while but subsequent builds will be very fast due to dockers caching. Then we can run the container with.

docker run -t -i eduonix/golangtools:1.0.0

If everything has worked you should see the following files in the bash terminal after typing ls
1

We will start with a simple Hello World program to illustrate the build steps then we will run a simple server. Then we will set up a fully-fledged rest server in our container and access it with a JBoss resteasy client.

Now we will run the code highlighting the key points along the way.

To build the Hello World application hworld.go we issue the command

go build -x hworld.go
./hworld

The key points here are firstly to create a runnable Go executable we must be in the ‘main’ package and the ‘-x’ flag will print out every step as it executes them.

2
Here we can see everything has built correctly and are Go development environment is configured.

Type exit to shut down then delete the container.

Build a Simple Server with Go and Docker

No we will build a simple server simpleserver.go. To do this we need to open a port to our container, we will use the -p flag to open a port

Run the image with

docker run -t  -i  -p 8000:8000 eduonix/golangtools:1.0.0

Build and run the server with

go build -x simpleserver.go
./simpleserver

3

Now we see the server is waiting to serve requests, if we open a browser and go to https://localhost:8000/

4

We can see with Go’s extremely efficient and clean syntax how we can rapidly develop web applications with close to zero compile time.

If we look at the source file simpleserver.go in the main package for the first simple rest server application we can see some of Go’s syntax which we highlight

package main   // 1

import (       // 2
  "io"
  "net/https"
)


func hello(w https.ResponseWriter, r *https.Request) {
  io.WriteString(w, "Hello world!")
}
						// 3
func main() {
  https.HandleFunc("/", hello)
  https.ListenAndServe(":8000", nil)
}

We can immediately see that Go follows the syntax of the C family of languages and it implements the best features, There are many resources to learn the complete Go syntax, but stepping through the code we can see

1. the package system is declared relative to $GOPATH/src, in our Dockerfile the path /gopath/src/main/ takes us to the runnable package ‘main’
2. the import statements, to import our own homegrown packages we declare them relative to o $GOPATH/src
3. Go has functions and a entrypoint main function as in C or Java
4. The import block

import (       // 2
  "io"
  "net/https"
)        

manages dependencies relative to the GOPATH

Please note when we build and run the Go code in the Dockerfile the package structure is finalised with the Docker instruction(s)

ADD main/ /gopath/src/main/
ADD restserver/ /gopath/src/restserver/

Set up a Professional Rest Development Environment with Go

The package in the source restserver is adapted from Sleepy an Open Source Go Rest implementation released under the MIT license that is ideal for bootstrapping a Proffessional Rest backend.

The package in the source go-rest-client is an implementation of the latest JAX-RS 2.0 Client API using the JBoss Resteasy framework.

Run the docker Go container with publishing the port for the server

docker run -t  -i  -p 8000:8000 eduonix/golangtools:1.0.0

Build and run the rest server application with

go build -x restserver.go
./restserver

5
You can see its waiting for rest calls to respond to, so now build and run the GoRestClient below

public interface GoRestClient {
   @GET
   @Path("/items")
   @Produces("application/json")
   String getItems();
}

and the Go rest server responds
6
Looking at the restserver.go source file we see a similar pattern to our simpleserver.go source file.
In the import block

import (
  "net/url"
  "net/https"
  "restserver"
)

We have added an import relative to the GOPATH to the source file serverengine.go in the “restserver” package which is in the folder with the same name relative to the GOPATH

We have created a go function func (item Item) Get( which uses Go simple but powerful type system to implement the Get type we have declared in the “restserver” package in the serverengine.go source

type GetSupported interface {
  Get(url.Values, https.Header) (int, interface{}, https.Header)

The Go rest server using a type API struct allows us to define API(s) for the rest server

type API struct {
  mux     *https.ServeMux
  muxInitialized bool
}

Hopefully you can see how we can quickly bootstrap a rest backend for our JAX-RS 2.0 Client API client implemented using the JBoss Resteasy framework using Go’s simple type system.

No we are in a position to develop the Go rest server back end and extend the Java rest client to implement the front end. We can do this painlessly on our development box and when we are ready push the Docker container to production.

It is hoped this set up can bootstrap your Rest Server Go development application.

So far in this series of articles we have looked at build tools and system programming, Go is a simple powerful language for just about anything except Graphical User Interfaces (GUI) and application front ends.
In the next series of articles we will look at front end technologies. We will start by using the system programming tools to see ways to implement native code in front end architectures.

1 COMMENT

  1. If some one desires expert view on the topic of blogging and site-building then i
    propose him/her to pay a visit this blog, Keep up the pleasant job.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -