Home > Articles

  • Print
  • + Share This
This chapter is from the book

Scaffolding a Microservice

In a perfect world, we would start with a completely blank slate and go directly into testing. The problem with ideal, perfect worlds is they rarely ever exist. In our case, we want to be able to write tests for our RESTful endpoints.

The reality of the situation is we can’t really write a test for RESTful endpoints unless we know what kind of functions we’re going to be writing per endpoint. To figure this out, and to get a basic scaffolding for our service set up, we’re going to create two files.

The first file, main.go (Listing 5.2), contains our main function, and creates and runs a new server. We want to keep our main function as small as possible because the main function is usually notoriously hard to test in isolation.

Listing 5.2 main.go

package main

import (
  service "github.com/cloudnativego/gogo-service/service"

func main() {
  port := os.Getenv("PORT")
  if len(port) == 0 {
    port = "3000"

  server := service.NewServer()
  server.Run(":" + port)

The code in Listing 5.2 invokes a function called NewServer. This function returns a pointer to a Negroni struct. Negroni is a third-party library for building routed endpoints on top of Go’s built-in net/http package.

It is also important to note the bolded line of code. External configuration is crucial to your ability to build cloud native applications. By allowing your application to accept its bound port from an environment variable, you’re taking the first step toward building a service that will work in the cloud. We also happen to know that a number of cloud providers automatically inject the application port using this exact environment variable.

Listing 5.2 shows our server implementation. In this code we’re creating and configuring Negroni in classic mode, and we’re using Gorilla Mux for our routing library. As a rule, we treat any third party dependency with skepticism, and must justify the inclusion of everything that isn’t part of the core Go language.

In the case of Negroni and Mux, these two play very nicely on top of Go’s stock net/http implementation, and are extensible pieces of middleware that don’t interfere with anything we might want to do in the future. Nothing there is mandatory; there is no “magic”, just some libraries that make our lives easier so we don’t spend so much time writing boilerplate with each service.

For information on Negroni, check out the GitHub repo https://github.com/codegangsta/negroni. And for information on Gorilla Mux, check out that repo at https://github.com/gorilla/mux. Note that these are the same URLs that we import directly in our code, which makes it extremely easy to track down documentation and source code for third-party packages.

Listing 5.3 shows the NewServer function referenced by our main function and some utility functions. Note that NewServer is exported by virtue of its capitalization and functions like initRoutes and testHandler are not.

Listing 5.3 server.go

package service

import (


// NewServer configures and returns a Server.
func NewServer() *negroni.Negroni {

        formatter := render.New(render.Options{
                IndentJSON: true,

        n := negroni.Classic()
        mx := mux.NewRouter()

        initRoutes(mx, formatter)

        return n

func initRoutes(mx *mux.Router, formatter *render.Render) {
        mx.HandleFunc("/test", testHandler(formatter)).Methods("GET")

func testHandler(formatter *render.Render) http.HandlerFunc {

        return func(w http.ResponseWriter, req *http.Request) {
                formatter.JSON(w, http.StatusOK,
                 struct{ Test string }{"This is a test"})

The most important thing to understand in this scaffolding is the testHandler function. Unlike regular functions we’ve been using up to this point, this function returns an anonymous function.

This anonymous function, in turn, returns a function of type http.HandlerFunc, which is defined as follows:

type HandlerFunc func(ResponseWriter, *Request)

This type definition essentially allows us to treat any function with this signature as an HTTP handler. You’ll find this type of pattern used throughout Go’s core packages and in many third-party packages.

For our simple scaffolding, we return a function that places an anonymous struct onto the response writer by invoking the formatter.JSON method (this is why we pass the formatter to the wrapper function).

The reason this is important is because all of our RESTful endpoints for our service are going to be wrapper functions that return functions of type http.HandlerFunc.

Before we get to writing our tests, let’s make sure that the scaffolding works and that we can exercise our test resource. To build, we can issue the following command (your mileage may vary with Windows):

$ go build

This builds all the Go files in the folder. Once you’ve created an executable file, we can just run the GoGo service:

$ ./gogo-service
[negroni] listening on :3000

When we hit http://localhost:3000/test we get our test JSON in the browser, and we see that because we’ve enabled the classic configuration in Negroni, we get some nice logging of HTTP request handling:

[negroni] Started GET /test
[negroni] Completed 200 OK in 212.121μs

Now that we know our scaffolding works, and we have at least a functioning web server capable of handling simple requests, it’s time to do some real Test-Driven Development.

  • + Share This
  • 🔖 Save To Your Account