forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exercise1.go
80 lines (63 loc) · 1.53 KB
/
exercise1.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package cmduser
import (
"encoding/json"
"github.com/spf13/cobra"
)
var getLong = `Use get to retrieve a user from the system.
Example:
./shelf user get -e "bill@ardanlabs.com"
`
// get contains the state for this command.
var get struct {
email string
}
// addCreate handles the creation of users.
func addCreate() {
cmd := &cobra.Command{
Use: "get",
Short: "Get retrieve a user from the system.",
Long: getLong,
Run: runGet,
}
cmd.Flags().StringVarP(&get.email, "email", "e", "", "Email for the user.")
// THIS WILL BE AVAILABLE WHEN IN THE SAME PACKAGE.
//userCmd.AddCommand(cmd)
}
// runGet is the code that implements the create command.
func runGet(cmd *cobra.Command, args []string) {
cmd.Printf("Getting User : Email[%s]\n", get.email)
if get.email == "" {
cmd.Help()
return
}
u, err := getUser(get.email)
if err != nil {
cmd.Println("Getting User : ", err)
return
}
data, err := json.MarshalIndent(&u, "", " ")
if err != nil {
cmd.Println("Getting User : ", err)
return
}
cmd.Printf("\n%s\n\n", string(data))
}
//==============================================================================
// User represents a sample user model.
// NEED THIS FOR THE EXERCISE TO BUILD.
type User struct {
Status int
Name string
Email string
Password string
}
// createUser is a sample function to simulate a user creation.
func getUser(email string) (*User, error) {
u := User{
Status: 1,
Name: "Bill",
Email: "bill@ardanlabs.com",
Password: "my passoword",
}
return &u, nil
}