How-tos

Write your first Golang app server on Bluemix

Share this post:

Golang is gaining more and more traction in the tech industry and is a really cool and powerful language. This quick introduction goes over some the benefits of Golang (Go) and explains the steps for building and deploying a Go starter app in Bluemix.

Quick introduction to Golang (Go)

Go was/is a language that has been mostly developed and maintained by Google, but recently a lot of other companies have been adopting it as well. Little known fact here is if you are using Bluemix, which is built on Cloud Foundry, you are using Go and you probably didn’t even know it. A lot of Cloud Foundry is being currently rewritten in Go that was previously written in Ruby. Additionally the Cloud Foundry CLI is written in Go as well.

As of late 2014, GitHub has over 22,000 repositories that are Go projects. Go first appeared on GitHub in 2009. The growth rate of Go in GitHub is impressive:

Golang’s history can be traced back to a research project from 2007 that was founded out of hatred of C++. The original authors had gripes with C++ over its complexity, missing concurrency support, scalability, and really long build times. Golang was built to address these shortcomings with C++. Golang was open sourced in late 2009.

Why should I use Go?

So you might be asking yourself: Why should I use Go? Why are all these companies now using it? Why is there so much growth in the language? The answer is simple—it’s freakishly fast!

The way Go handles concurrent asynchronous programming is sublime. Another big draw to Go is the syntax is modern as well. Go has a lot of things from C in the language, but it makes some of those things I did not like in C a lot more manageable. One of the most powerful things in Go is the parsing of JSON. For example, with the following data structure you can cast JSON in and out of a data structure:

type Dealership struct {
    Name      string   `json:"name"`
    Cars     []string  `json:"cars"`
}

The above data structure would parse a JSON instance like the following.

{
    "name": "John",
    "cars": [
        "Bugatti",
        "Ferrari",
        "Tesla"
    ]
}

Pretty powerful huh? A really cool note here is Go can cast a data structure to JSON or cast JSON into a data structure.

Another really nice draw to Go is the packaging and licensing. Go has a powerful plugin/library system—you can basically import any Git repo into Go as a package. For example, the following lines are importing some core packages from Go called os and net/http. It is also importing a package from GitHub as well:

import (
    "github.com/gin-gonic/gin"
    "net/http"
    "os"
)

Sample Go app in Bluemix

With some background on Go out of the way, now let’s jump into a sample Go app in Bluemix. For this brief tutorial, I’ll present two ways of deploying the sample app to Bluemix. The first is the easiest way to get up and running for demonstrations; the second is the more developer-oriented approach that allows easy code modifications.

To begin, let’s review some of the application code. The app that we will be using is available in the project go-hello-world on GitHub. Let’s walk through the code and I will explain what is going on. We are going to be looking at go-hello-world.go.

The first lines we are going to look at are 1-7, the lines are shown below and the source is in go-hello-world.go.

Line 1 introduces the concept of a package; the package name corresponds to the entry point of the application, for this case the main entry point is the main method.

Lines 3-7 import some various packages; github.com/gin-gonic/gin is a package from GitHub while os and net/http are core packages.

Let’s review the big block of code next. Don’t let it scare you, it’s actually not too bad:

Line 1 introduces the notion of a function/co-routine.

Line 2 initializes a variable called router that is part of the gin-gonic package. The gin-gonic is a router and also template engine; if you are coming from Node land, think of it like Express.

router := gin.Default()

Line 3 tells the router to serve templates out of a directory called templates.

router.LoadHTMLGlob("templates/*")

The templates directory contains a file called index.tmpl. The file looks like the following:


In this file you will see {{ .title }}; it means title will get replaced with a variable when the template is rendered.

Lines 5-9 will render the index.tmpl template.

Line 5 tells Go when a request that comes for the root directory /, it will be routed to this function.

router.GET("/", func(c *gin.Context) {

Lines 6-8 will send a HTTP response and replace the variable title in the template.

c.HTML(http.StatusOK, "index.tmpl", gin.H{
        "title": "Main website",
})

The page will will just return a simple HTML page that says “Main website”.

Lines 11-15 will return a JSON response on /hi. The JSON that will be returned is the following.

{
    "message": "hi"
}

Lines 17-20 will decide if the app is running in Bluemix or if the app is running locally.

port := os.Getenv("VCAP_APP_PORT")
if port == "" {
    port = "8080"
}

Lastly, line 21 will start the webserver.

router.Run(":" + port)

Deploying the sample Go app

As I mentioned earlier, there are two ways to do this:

  • Deploying via the “Deploy to Bluemix” button
  • Downloading go and building the app and using the Cloud Foundry CLI

The first is probably the easiest of the two if you want to get started really quickly but the second one should be used if you want to modify the code.

Deploy to Bluemix button

Open your web browser and click go-hello-world. You will be taken to GitHub. Scroll down a bit and click on the blue button that says “Deploy to Bluemix”. This path will do everything that is needed to deploy the app. A Git repository will be created for you, the Go dependencies will be installed, the Go binary will be built, and the binary will be deployed to Bluemix for you.

Deploy by downloading and building the code locally

  • If you don’t have Go installed, install it
  • If you don’t have a Bluemix account, sign up for Bluemix
  • Download and install the Cloud Foundry CLI tool
  • Change to the GOPATH directory: cd $GOPATH
  • Clone the app to your local environment: git clone https://github.com/IBM-Bluemix/go-hello-world.git
  • Change to the newly created directory: cd go-hello-world
  • Compile the Go code: make
  • Open the manifest.yml file and change the host value to something unique. The host you choose will determinate the subdomain of your application’s URL: <host>.mybluemix.net
  • Connect to Bluemix using the cf CLI: cf api https://api.ng.bluemix.net
  • And then log into Bluemix: cf login
  • Deploy your app to Bluemix: cf push

That’s it! Your application should now be running on http://<host>.mybluemix.net.

I would love to hear your feedback and any suggestions you have, please reach out to me on Twitter @jsloyer.

IBM Cloud Containers Service - Core Dev Lead

More stories

How to Backup Your IBM Cloud Linux Server

This post covers how to backup entire partitions in Linux systems. The process utilizes the tar command in IBM Cloud's unique rescue environment and showcases the simplicity and flexibility of the process.

Continue reading

Part II: Wimbledon Facebook Bot on IBM Cloud

In the second in a series of posts about how IBM iX designed, developed, and delivered the Facebook Messenger Bot available at Wimbledon 2018, we focus on the broadcast integration within Facebook and how we persisted user preferences using IBM Cloudant and Compose Redis.

Continue reading

Speed up your WordPress with IBM Cloud

WordPress is one of the most popular content management systems available, but the many websites and blogs that use it experience issues with speed. At IBM Cloud, there are several solutions that can help alleviate some of these issues and allow you to have a better and faster WordPress experience.

Continue reading