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.

Add Comment
2 Comments

Leave a Reply

Your email address will not be published.Required fields are marked *


Subbarao Seethamsetty

Jeff Sloyer, Thank you very much for the excellent peek at using GO in Bluemix – We will probably use this as demo for BlueMix at an event at RIT, Rochester, NY that is coming up in a week.

Reply

Madars Vitolins

Check out Enduro/X Application Server for GO. It allows to build application by components, where each component is separate Go binary.

Reply
More How-tos Stories

Build and deploy a MEAN stack application on IBM Cloud

MEAN is a collection of JavaScript-based technologies — MongoDB, Express.js, AngularJS, and Node.js — used to develop web applications. From the client and server sides to databases, MEAN is a full-stack development toolkit. This tutorial walks you through the creation of a web application using the popular MEAN stack. It is composed of a Mongo DB, Express web framework, Angular front-end framework and a Node.js runtime.

Continue reading

A hybrid Cordova mobile app with Push and Analytics in minutes

As promised while introducing "Tutorials to get your mobile development up and running", we are continuing our efforts to add more mobile solution tutorials. After quickly scaffolding a native iOS-Swift and Android mobile app with Push and Analytics, it's time to bring in the hybrid mobile app development flavor to the game with Cordova - Apache Cordova is an open-source mobile development framework. It allows you to use standard web technologies - HTML5, CSS3, and JavaScript for cross-platform development.

Continue reading

Use your own branded UI for user sign-in with App ID

With IBM Cloud App ID’s Cloud Directory feature, you can create a user registry, and add sign-up and email/password sign-in to your mobile or web app. Cloud Directory comes with a pre-built sign-in widget that you can use, or if you prefer to use your own branding, you can replace it with your own custom UI. This blog will show you how to use Cloud Directory APIs and add your own custom sign-in screen to an Android application. You can find the Android Cloud Land App on GitHub.

Continue reading