How To Create A Simple RESTful Service In Go

One of sweet spots of Golang is building RESTful services. Standard library package net/http provides all we need to build a simple one, and in this post we will see how easy it is.

For production code, I would highly recommend to have a look at gorilla/mux, which is widely adopted in the field. And if you need to build a RESTful service with context and middleware support, have a look at RESTful web service in Go using Goji.

A Hello World RESTful service

package main

import (  
        "fmt"
        "net/http"
)

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

func hello(w http.ResponseWriter, r *http.Request) {  
        name := r.FormValue("name")
        if len(name) == 0 {
                name = "Stranger"
        }
        fmt.Fprintf(w, "Hello, %v", name)
}

The code creates and runs a web service listening on port 8080.

GET http://localhost:8080/hello will return

Hello, Stranger  

and GET http://localhost:8080/hello?name=Jack will result in

Hello, Jack  

To get source from GitHub run:

go get github.com/upitau/goinbigdata/examples/hellorest  

How it works

func main

Notice how easy it is to create and start a web server. We just need to:
1. Register function hello to handle requests for path /hello
1. Create and run a web server listening on a specified port

func hello

This function simply checks if parameter name is provided in url and if not, initializes it with value "Stranger". Then it returns a greeting.

Bottom line

A RESTful service in Go could be as simple as handful of lines of code. Even though the example is deliberately simplified to show the essence, writing more complex RESTful service would not be significantly different.

comments powered by Disqus