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 package main
 2 
 3 import (
 4   "encoding/json"
 5   "net/http"
 6 )
 7 
 8 type Member struct {
 9   Login string
10   Email string
11 }
12 
13 func handler(w http.ResponseWriter, r *http.Request) {
14   member := Member{"someuser", "someuser@somedomain.com"}
15   j, _ := json.Marshal(member)
16 
17   w.Header().Set("Content-Type", "application/json")
18   w.Write(j)
19 }
20 
21 func main() {
22   http.HandleFunc("/", handler)
23   http.ListenAndServe(":8080", nil)
24 }

Then:

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

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