rodrigosaito.com

home

JSON responses in Go

02 May 2015

On the previous part of this tutorial I showed how to create a Hello World Webserver in Go, in this part I will demonstrate how to return JSON responses using the standard library.

Let’s modify our previous example and generate a JSON response instead of a hardcoded string:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

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

type Member struct {
  Login string
  Email string
}

func handler(w http.ResponseWriter, r *http.Request) {
  member := Member{"someuser", "someuser@somedomain.com"}
  j, _ := json.Marshal(member)

  w.Header().Set("Content-Type", "application/json")
  w.Write(j)
}

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

Then:

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

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