JSON

To explore how to work with remote data from a web service, we shall start by adapting our web service example from Chapter 3, Go to the Rescue!. The code is slimmed down and updated to use the same readStream() function as created for the preceding image example. The resulting code is very basic but demonstrates how easily we can decode JSON data into a struct using built-in Go features:

type Person struct {
Title string `json:"title,omitempty"`
Firstname string `json:"firstname"`
Surname string `json:"surname"`

Username string `json:"username"`
Password string `json:"-"`
}

func
main() {
fmt.Println("Downloading...")
stream := remote.ReadStream("http://echo.jsontest.com/title/Sir/" +
"firstname/Tom/surname/Jones/username/singer1/")
defer stream.Close()

person := &Person{}
json.NewDecoder(stream).Decode(person)
fmt.Println("Decoded:", person)
}

Using a single method for our resource loading enables us to put more robust error handling in a central place. Until we've made those improvements, our application will crash if the request fails (no internet or server error, for example):

Image failure when there's no network connection
JSON can't be accessed when offline either

While these errors could be handled better, we would still have downloaded no content. An image not loading may not matter, situations when the connection but missing JSON data would probably reduce the functionality of our application. What we should aim for is to better handle situations where the connection isn't present or isn't responding correctly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.124.21