rodrigosaito.com

home

Rest API in Go

03 May 2015

On the previous post we learned how to return JSON responses in Go, now we will see how to build our first Rest API.

Let's modify our previous example to have a route to handle the member resource:

 1 package main
 2 
 3 import (
 4         "encoding/json"
 5         "io/ioutil"
 6         "net/http"
 7 )
 8 
 9 var members = []Member{Member{"someuser", "someuser@somedomain.com"}}
10 
11 type Member struct {
12         Login string
13         Email string
14 }
15 
16 func main() {
17         http.HandleFunc("/members", membersHandler)
18         http.ListenAndServe(":8080", nil)
19 }
20 
21 func membersHandler(w http.ResponseWriter, r *http.Request) {
22         w.Header().Set("Content-Type", "application/json")
23 
24         if r.Method == "GET" {
25                 j, _ := json.Marshal(members)
26 
27                 w.Write(j)
28         }
29 
30         if r.Method == "POST" {
31                 var m Member
32                 b, _ := ioutil.ReadAll(r.Body)
33                 json.Unmarshal(b, &m)
34 
35                 members = append(members, m)
36 
37                 j, _ := json.Marshal(m)
38                 w.Write(j)
39         }
40 }

On line 17 we changed the first parameter from "/" to "/members", now our membersHandler will only handle requests to the /members endpoint.

The membersHandler function:

When we issue a GET /members then we will see the following response:

$ curl -i localhost:8080/members
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 56

[{"Login":"someuser","Email":"someuser@somedomain.com"}]%

We can also create a new member:

$ curl -d '{"Login":"anotheruser", "Email": "another@somedomain.com"}' -i localhost:8080/members
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 56

{"Login":"anotheruser","Email":"another@somedomain.com"}%

The following posts I will show you how to have smarter routes and how to persist your members using MongoDB.