Web services included as standard

As a modern programming language, Go comes with extensive support for HTTP clients, servers, and standard encoding handlers, including JSON and XML. Combined with the built-in string and map features, this removes many of the hurdles of working with web services. In addition to this, the format for structs in Go allows for additional tags that can provide metadata to its fields. Both the encoding/json and encoding/xml packages make use of this to understand how to correctly encode and decode instances of these structs. The following example demonstrates these features by connecting to a web service, accessing a JSON response, and decoding it into a struct that is then used like any other:

package main

import "encoding/json"
import "fmt"
import "io/ioutil"
import "net/http"

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

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

func readFromURL(url string) ([]byte, error) {
var body []byte
resp, err := http.Get(url)
if err != nil {
return body, err
}

defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}

func main() {
person := &Person{
"",
"John",
"Doe",
"someuser",
"somepassword",
}
fmt.Println("Struct:", person)

data, _ := json.MarshalIndent(person, "", " ")
fmt.Println("JSON:", string(data))

fmt.Println("Downloading...")
data, _ = readFromURL("http://echo.jsontest.com/title/Sir/" +
"firstname/Anthony/surname/Other/username/anon123/")
fmt.Println("Download:", string(data))

person = &Person{}
json.Unmarshal(data, person)
fmt.Println("Decoded:", person)
}

In the preceding example code you can see the usage of struct tags prefixed with "json:". These provide hints to the "encoding/json" package that manages the encoding and decoding of theses objects. We can run this example and see the output of converting a struct into JSON and back again:

Encoding and decoding JSON for an HTTP request

Notice that zero value fields marked with omitempty were not included in the JSON output, and equally the password field that was marked as "-" (meaning do not include) was ignored when encoding the data. After downloading the data from a test web service, it was marshaled directly into an instance of the Person struct, leaving missing fields with their zero value. This was all possible using built-in features of the language and standard library. It's very straightforward, thanks to Go's readiness for working with web services.

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

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