Programming language Go is one of a handful of popular, new ones aimed at modernizing conventional programming style established by C++ and Java. Go was originally designed at Google in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson.

There’re many things that make Go a very interesting language. Some of them that I personally appreciate include:

  • Compilation to optimized, statically linked native binaries without external dependencies.
  • Automatic memory management
  • Goroutines-based concurrency.
  • Native support for HTTP.
  • Built-in package manager: http://godoc.org/

As an introduction to Go language (or: “Golang”), let’s see an example of a very simple web API outputting: “Hello Web” JSON message.

Code

package main

import (
  "fmt"
  "net/http"
)

func main() {
  http.HandleFunc("/hello", viewHandler)
  http.ListenAndServe(":8080", nil)
}

func viewHandler(w http.ResponseWriter, r *http.Request) {  
  w.Header().Set("Content-type", "text/plain")
  
  fmt.Fprintf(w, jsonMsg)
}

Creating a more common JSON output takes a little more code:

package main

import (
  "fmt"
  "net/http"
  "time"
  "encoding/json"
)

func main() {
  http.HandleFunc("/hello", viewHandler)
  http.ListenAndServe(":8080", nil)
}

func viewHandler(w http.ResponseWriter, r *http.Request) {  
  w.Header().Set("Access-Control-Allow-Origin", "*")
  w.Header().Set("Content-type", "application/json")  
  
  jsonMsg, err := getResponse() 
  if err != nil {
    http.Error(w, "Oops", http.StatusInternalServerError)
  }
  fmt.Fprintf(w, jsonMsg)
}

func getResponse() (string, error){
  unixtime := int32(time.Now().Unix())
  msg := Message{"Hi", "Hello Web!", unixtime}
  jbMsg, err := json.Marshal(msg)

  if err != nil {    
    return "", err
  }

  jsonMsg := string(jbMsg[:]) // converting byte array to string
  return jsonMsg, nil
}

type Message struct {
  Title string
  Body string
  Time int32
}

How to Execute

Installing Go is easy on Mac. If you are using the Homebrew package manager, you can install Go by simply running:

brew install go

If you save the source of the web API code above in a file called server.go you can directly run it with:

go run server.go

or, you can first build the source to a binary executible with:

go build server.go

and then run with:

./server

You will be able to see the result in action, by pointing a browser to: http://0.0.0.0:8080/hello

Further Reading