Video icon 64
Learn to Code. Start your free trial today.
Advertisement

Start Developing With Go on the Mac

by
Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →
Final product image
What You'll Be Creating

Web applications are a part of life these days. The Go language, by Google, is a useful language to make web-based applications. I'll show you how to get started using Go on a Mac.

Setting Up the Go Environment

The easiest way to install the Go programming language is by Homebrew. If you haven’t installed Homebrew yet, the tutorial Homebrew Demystified: OS X’s Ultimate Package Manager will show you how.

In a terminal, type:

brew install go
Finding the go Install

To find the location of the go install directory, type this command in to your terminal program:

ls -la `which go`

You should get this result:

lrwxr-xr-x  1 raguay  wheel  25 May 14 15:11 /usr/local/bin/go -> ../Cellar/go/1.2.2/bin/go

This shows that the main installation of Go is /usr/local/Cellar/go/1.2.2. You need to setup the environment variable GOROOT to be the libexec directory of that directory.

In the home directory, create the directory go. The go language will store all downloaded packages there. Add to your .bashrc file and/or .zshrc file this line:

export GOPATH="/Users/<your user name>/go"
export GOROOT="/<your go installation>/libexec"

If you’re using fish, add this to your config.fish file:

set -xg GOPATH "/Users/<your user name>/go"
set -xg GOROOT "/<your go installation>/libexec"

To test go, type the following in a terminal:

go version

It should print out the version, of go, that is installed. On my system right now, it shows go version go1.2.2 darwin/amd64.

To check for newer versions, let HomeBrew figure that out. On the command line, type:

brew update
brew upgrade

The update command will get a list of updated programs. The upgrade command does the actual upgrade. This way, you never have to hunt the different web sites to find updates.

Setting Up the Editor

Now that Go is on the system, you need to set up the editor. I use Sublime Text 3, Vim, and Emacs a lot. Therefore, I need to get my editors up to speed with Go.

For Sublime Text, it’s easy. Install Package Manager for Sublime Text. This allows for easy package installations. The package you want to install is goSublime. goSublime gives you Go language syntax highlighting and a Go build system.

To install Go syntax highlighting for Emacs, install the eLisp routines found in $GOROOT/misc/emacs to your emacs elisp folder. For Emacs to load the new files, you add this line to the .emacs file in the home folder:

(require 'go-mode-load)

The support for Vim takes more work. In a terminal, run these bash command lines:

mkdir -p $HOME/.vim/ftdetect
mkdir -p $HOME/.vim/syntax
mkdir -p $HOME/.vim/autoload/go
ln -s $GOROOT/misc/vim/ftdetect/gofiletype.vim $HOME/.vim/ftdetect/
ln -s $GOROOT/misc/vim/syntax/go.vim $HOME/.vim/syntax
ln -s $GOROOT/misc/vim/autoload/go/complete.vim $HOME/.vim/autoload/go
echo "syntax on" >> $HOME/.vimrc

The last line is only needed if you do not already have syntax on in your .vimrc.

Libraries and How to Use Them

Traditionally, libraries are the basics of modularizing code for re-use. In go, libraries are packages. The go language comes with many packages built-in. You can scan through them on the packages page. There are also many 3rd party packages and projects.

For the Title Case Server, I am going to use the third-party package web.go. It’s a simple web server framework that simplifies the creation of web based applications in Go. To load that package on your system, type the following:

go install github.com/hoisie/web

The install command takes an argument that’s a web address, without the http://, for a package to download. It’s placed in the $GOPATH directory that was created earlier.

The Project: Title Case Server

Title case is one of the most picky things. Some people like certain words always lower case. Others think words should be all title case. Therefore, to do it properly (which most package routines do not do), you have to check each word against two dictionaries of words to get everything right. It makes a great beginner project in a new programming language.

//
// Package:       Main
//
// Description:  This is the main package for the goTitleServer.
//		      This is a simple web technology based title case
//                     text server.
//
package main

The // symbol denotes a comment. The compiler ignores everything after that in the line. I like to comment everything. When you read the code years later, the comments help you to remember how the program works.

The line after the comments is the package declaration. Every file that Go uses has to be a part of a package. Each program has only one main package that has to have the main() function. That tells the compiler where to start to run the program.

//
// Import the libraries that we need for the server.
//
import (
	"github.com/hoisie/web"
	"os"
	"strings"
)

To make use of packages, you have to import them. All of the packages used have to be in this statement. I am including the two base packages of os for the operating system functions, and strings for manipulating strings. The github.com/hoisie/web loads the web.go package for making the web server.

//
// Function:             homePage
//
// Description:         This function will server the home page for inputing the string
//                             to convert.
//
func homePage() string {
    return `
<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>Title Case Server</title>
		<!--[if IE]>
			<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js">
			</script>
		<![endif]-->
		<style>
			body {
				width:		100%;
			}

			header {
				background: 	lightblue;
				width:		80%;
				height:		100px;
				margin:		20px auto;
				border-radius:	10px;
			}

			header h3 {
				text-align:		center;
				padding-top:	40px;
				font-size:		28px;
			}

			content {
				font-size:		16px;
			}

			content form {
				font-size:		inherit;
				margin:		auto;
				padding-left:	8px;
				width:		80%;
				text-align:		center;
			}

			content form p input {
				width:		80%;
			}

			content form button {
				margin: 		auto;
				border-radius:	10px;
			}
		</style>
 		<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js">
 		</script>
 		<script type="text/javascript" >
 			window.convert = function() {
 				$.ajax({
 					type: "GET",
 					url: "http://127.0.0.1:9910/titlecase/",
 					data: { text: $("#text").val()}
 				}).done(function(msg) {
	 				$("#result").val(msg);
 				});
 			};
		</script>
	</head>
	<body>
 		<header>
 			<h3>Title Case Server</h3>
 		</header>
 		<content>
 			<form action="/titlecase/" method="get">
 				<p>Text to fix:
 					<input id="text" type="text" name="text" >
 					</input>
 				</p>
 				<button type="button" id="convert" text="Convert" onclick="window.convert();">Convert</button>
 				<p>Results:
 					<input id="result" type="text" name="result">
 					</input>
 				</p>
 			</form>
 		</content>
 		<footer>
 		</footer>
	</body>
</html>
	`
}

This function creates the home page. This is what the server gives to a web browser that requests the front page of the web site. The func command is a function declaration. The homePage is the name of the function. The () tells the compiler that this function does not take any inputs. The string after the parenthesis tells the compiler that the function will return a string.

Everything inside of the {} is the code for the function. This function is simple: return the quoted string to the caller of the function. In go, you can quote strings with "", ’’, and ``. I used the last one here to have a multiple line string that’s not processed at all. You call that a literal string.

By using the literal quote method, I can layout the web page just like I would normally. Nothing inside of the tick marks gets processed by the compiler. It’s copied directly in to the program, and the program returns it to the web browser upon request.

//
// Function:            titleCase
//
// Description:        This takes a string and converts it to Title case. It then
//                             returns the string.
//
// Input:
//                            val         rest of the url if given any.
//
func titleCase(ctx *web.Context, val string) string {
    //
	// Get the string to convert and split it up by spaces.
	//
	words := strings.Split(ctx.Params["text"], " ")

	//
	// The array of words that should be lower case always, unless it is the first word
	// of the title.
	//
	lower := [...]string{"to", "an", "and", "at", "as", "but", "by", "for", "if", "in", "on", "or", "is", "with", "a", "the", "of", "vs", "vs.", "via", "via", "en"}

	//
	// The array of words that should be all upper case always.
	//
	upper := [...]string{"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "HTML", "CSS", "AT&T", "PHP"}

	//
	// For every word in the Title.
	//
	for i, _ := range words {
		//
		// Assume the word is not in the upper case or lower case arrays.
		//
		up := false
		low := false

		//
		// Loop through every word in the lower case array.
		//
		for j, _ := range lower {
			if strings.ToLower(words[i]) == lower[j] {
				//
				// It matches. Make sure the word in the array is the same.
				// Set the up flag as true.
				//
				words[i] = lower[j]
				low = true
			}
		}

		//
		// Loop through every word in the upper case array.
		//
		for k, _ := range upper {
			if strings.ToUpper(words[i]) == upper[k] {
				//
				// It matches. Make sure the word is the array is the same.
				// Set the low flag to true.
				//
				words[i] = upper[k]
				up = true
			}
		}

		//
		// If the word was not in the upper or lower array, then do a normal
		// title case conversion. This makes the first letter upper case and all
		// the other letters lower case.
		//
		if (!up) && (!low) {
			words[i] = strings.Title(words[i])
		}
	}
	//
	// Make sure the first word is title case!
	//
	words[0] = strings.Title(words[0])

	//
	// Return the Title by joining all the words with a space.
	//
	return strings.Join(words, " ")
}

This code does the work of translating a string given to the web server in to the title case equivalent.

The ctx *web.Context, val string tells the compiler that this function receives two variables. One is a pointer to the web.Context data structure defined in the web.go package. The other is a string. You declare a variable input by a name and the type of variable.

The * symbol denotes a pointer. A pointer is an address to the location in memory for the data structure. Go follows C data pointer formats.

The first statement gets the parameter named text that the browser passes to the server and splits it up by spaces. The strings.Split calls the Split function inside of the strings package. You can think of packages similar to Objects in C++. You call them using a . between the package name and the function name.

In every package, each function that starts with a capital letter is accessible from outside the package. Every function that starts with a lower case letter is only accessible from inside the package.

When the strings.Split function splits up a string by the separator, it returns an array of strings. The output is then assigned to the variable words. To create a new variable, the first time it’s used, you must use a := to assign it. If you want to change the same variable to another array of strings, you would use the = operator.

Next, create two arrays for the different word lists. lower is for all lower case words, and upper for all the upper case words. The […] tells the compiler to get the number of assignments from the data. That way you can add words to the list without worrying about incrementing the count. The string tells the compiler that each entry in the array is a string.

I am using for..range loops to sequence over the arrays. The first one goes over every word given in the input, while two other loops go through each dictionary of words for each word. It first converts the word to lower case, compares it to each word in the lower dictionary. If there is a match, it forces the word to all lower case by assigning that word position to the string in the dictionary. It then does the exact same thing using the upper dictionary.

If the word was not in either dictionary, then it performs the strings.Title function to the word. This forces the first letter to be uppercase and all the rest lowercase.

Lastly, the first word made title case no matter what. The strings.Join function assembles the array of strings using a space. It returns the results to the caller of the function.

//
// Function:             killServer
//
// Description:         This function will stop the server.
//
func killServer() string {
	os.Exit(0)

	return ""
}

The killServer function does exactly what the name implies: kills the web server. It wraps a call to the os.Exit() function in the os package.

//
// Function:             main
//
// Description:         This is the main function that is called upon program running.
//
func main() {
    //
	// set the titlecase web address to the proper function.
	//
	web.Get("/titlecase/(.*)", titleCase)

	//
	// Set up a path to kill the server.
	//
	web.Get("/kill", killServer)

	//
	// send the home page to the proper function.
	//
	web.Get("/", homePage)

	//
	// Run the server on the local machine at port 9911
	//
	web.Run("127.0.0.1:9910")
}

The main function uses web.Get to set up the Get protocol routes for the home page, the kill page, and the title case converter routine. The web is the web.go package that we downloaded earlier. The Get defines a HTML Get request. There are also the Put, Post, and Delete operators that you can define.

The web.Run statement starts the web server on the given address and port. The web.go package takes over from there and calls your routines whenever the addresses defined get requested.

Compiling

Now that the program’s done, you need to compile it. To compile a Go program, you tell it to build the file with the main function. To compile this program, you type:

go build goTitleServer.go

When it finishes, you will have goTitleServer in the directory. That’s the full program. You can launch it with:

./goTitleServer

Then open a web browser to http://127.0.0.1:9910. You should see this:

goTitleServer Running

Enter your string in the Text to fix: text box, press Convert, and the converted string will appear in the Results: text box.

Title Case Server Workflow

I naturally put this program into an Alfred workflow. It’s a part of the download along with the goTitleServer.go file. This gives an example of using the server without a web browser. It uses the following bash code to query the server:

query=`echo "{query}" | sed -e 's/ /+/g'`;
curl "http://localhost:9910/titlecase/?text=$query";

The first line changes all the spaces in the query string to +. The curl command is a standard unix command for getting information from a web server. The command line will use the curl command a url request like the web page would create to send to it. What’s returned in the results from converting the string in to title case.

The Alfred prompt commands for this workflow are:

tis:launch–This command launches the server. You have to launched the server before you can convert.

tcs:convert–This command takes a string to convert. The workflow shows the result in a notification and copies it to the clipboard.

tcs:kill–This command kills the web server.

There’s also a hotkey that you need to assign to take the current selection and run it through the title case server and paste it back in place.

Conclusion

Now that you have the system configured to write and compile web applications using Go, you need to start writing some! Take this code base and expand it to more text processing functions to make a great text processing server.

Advertisement