The simplest REST JSON API in GO

Andriy Lesch
3 min readFeb 20, 2017

--

In this article we will see how to build simple REST API application using GO language. Later I am going to write about docker where we will reuse our REST API application.

So what you will need

For the first step You need to install GO on your PC (in my case I am using OS Windows 10), then install development environment(on my system it was installed Visual Studio Code )

GO GO :)

In our example we will use httprouter “gorilla/mux”. During your free time you can try to play with other httprouters just follow link and feel free to choose one.

Technical specification

Should be possible to do requests to our application :

1) Request GET - http://localhost:5000/
Response
"Welcome dear User!"
2) Request GET - http://localhost:5000/users/
Response JSON
[
{
"Id": 1,
"Nick": "test1",
"Email": "test1@gmail.com",
"Firstname": "FirstName1",
"LastName": "LastName1"
},
...
]
3) Request GET - http://localhost:5000/user/1
Response JSON
{
"Id": 1,
"Nick": "test1",
"Email": "test1@gmail.com",
"Firstname": "FirstName1",
"LastName": "LastName1"
}
4) Request POST - http://localhost:5000/user/1
Response JSON
{
"Message": "HTTP POST Method "
}
5) Request DELETE - http://localhost:5000/user/1
Response JSON
{
"Message": "HTTP DELETE Method "
}

Code

As you can see on image our project will have structure like

All source code you can download from github. Most important places in this project located in router.go file

package routersimport (
"net/http"
"simple-json-restapi/handlers"
"github.com/gorilla/mux"
)
type Route struct {
Name string
Methods []string
Pattern string
HandlerFunc http.HandlerFunc
}
var routes []Route// init method which will be automatically run
func init() {
// init root URL and handler function
routes = append(routes, Route{
Name: "Index",
Methods: []string{"GET"},
Pattern: "/",
HandlerFunc: handlers.Index,
})
/* init /user/{id} URL and handler function.
One handler function for three type of requests */
routes = append(routes, Route{
Name: "User",
Methods: []string{"DELETE", "GET", "POST"},
Pattern: "/user/{id}",
HandlerFunc: handlers.HandleUser,
})
/* init /users URL and handler function. */
routes = append(routes, Route{
Name: "Users",
Methods: []string{"GET"},
Pattern: "/users",
HandlerFunc: handlers.HandleUsers,
})
}
/* registering all url paths */
func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)for _, route := range routes {
var handler http.Handler
handler = route.HandlerFunc
router.
Methods(route.Methods...).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}
return router
}

and code for userHandler.go

package handlersimport (
"encoding/json"
"fmt"
"net/http"
"simple-json-restapi/managers"
"simple-json-restapi/models"
"strconv"
"github.com/gorilla/mux"
)
// handlerFunction for root URL
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Welcome dear User!")
}
// handlerFunction for /users/ url path
func HandleUsers(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
users := managers.GetUsers()json.NewEncoder(w).Encode(users)
}
// handlerFunction for /user/{id} url path
func HandleUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(r)
userId, err := strconv.Atoi(vars["id"])
if err != nil {
w.WriteHeader(http.StatusNotFound)
}
switch r.Method {case "GET":userItem := managers.GetUserById(userId)
json.NewEncoder(w).Encode(userItem)
case "DELETE":
json.NewEncoder(w).Encode(models.Result{
Message: fmt.Sprintf("HTTP %s Method", r.Method),
})
case "POST":
json.NewEncoder(w).Encode(models.Result{
Message: fmt.Sprintf("HTTP %s Method ", r.Method),
})
}
}

So as you can see in the code, it’s really easy. So let’s go to next step.

Build project

Open terminal in Visual studio code or just cmd, than build it to the same folder.

<YOUR PATH>\simple-json-restapi> go build 

*.exe file will be appeared in our folder

Let’s make test of our app

run “simple-json-restapi.exe” file and open link in browser http://localhost:5000 you will see

if you open http://localhost:5000/users/

So as you can see, our technical specification was successfully done. I hope this post was interesting for you. See you.

--

--

Andriy Lesch

Software Engineer | Full stack Developer (Asp.Net, C#, Angular, etc)