-
Notifications
You must be signed in to change notification settings - Fork 2
/
example1.go
59 lines (48 loc) · 1.23 KB
/
example1.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Copyright 2014 Ardan Studios
//
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// Sample program to show how functions can return multiple values while using
// named and struct types.
package main
import (
"encoding/json"
"fmt"
)
// user is a struct type that declares user information.
type user struct {
ID int
Name string
}
func main() {
// Retrieve the user profile.
u, err := retrieveUser("sally")
if err != nil {
fmt.Println(err)
return
}
// Display the user profile.
fmt.Printf("%+v\n", *u)
}
// retrieveUser retrieves the user document for the specified
// user and returns a pointer to a user type value.
func retrieveUser(name string) (*user, error) {
// Make a call to get the user in a json response.
r, err := getUser(name)
if err != nil {
return nil, err
}
// Unmarshal the json document into a value of
// the user struct type.
var u user
err = json.Unmarshal([]byte(r), &u)
return &u, err
}
// GetUser simulates a web call that returns a json
// document for the specified user.
func getUser(name string) (string, error) {
response := `{"id":1432, "name":"sally"}`
return response, nil
}
// Outputs:
// {ID:1432 Name:sally}