forked from GoesToEleven/GolangTraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
85 lines (78 loc) · 2.03 KB
/
main.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
81
82
83
84
85
package profile
import (
"html/template"
"io"
"net/http"
"os"
"google.golang.org/appengine"
"google.golang.org/appengine/datastore"
"google.golang.org/appengine/log"
"google.golang.org/appengine/user"
)
func init() {
http.HandleFunc("/", handle)
http.HandleFunc("/createProfile", createProfile)
}
// Profile holds user profiles
type Profile struct {
Email string
FirstName string
LastName string
}
func handle(res http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/" {
http.NotFound(res, req)
return
}
ctx := appengine.NewContext(req)
u := user.Current(ctx)
key := datastore.NewKey(ctx, "Profile", u.Email, 0, nil)
var profile Profile
err := datastore.Get(ctx, key, &profile)
if err == datastore.ErrNoSuchEntity {
http.Redirect(res, req, "/createProfile", http.StatusSeeOther)
return
} else if err != nil {
http.Error(res, "Server Error", http.StatusInternalServerError)
log.Errorf(ctx, err.Error())
return
}
tpl, err := template.ParseFiles("viewProfile.gohtml")
if err != nil {
http.Error(res, "Server Error", http.StatusInternalServerError)
log.Errorf(ctx, err.Error())
return
}
err = tpl.Execute(res, &profile)
if err != nil {
http.Error(res, "Server Error", http.StatusInternalServerError)
log.Errorf(ctx, err.Error())
return
}
}
func createProfile(res http.ResponseWriter, req *http.Request) {
ctx := appengine.NewContext(req)
if req.Method == "POST" {
u := user.Current(ctx)
profile := Profile{
Email: u.Email,
FirstName: req.FormValue("firstname"),
LastName: req.FormValue("lastname"),
}
key := datastore.NewKey(ctx, "Profile", u.Email, 0, nil)
_, err := datastore.Put(ctx, key, &profile)
if err != nil {
http.Error(res, "Server Error", http.StatusInternalServerError)
log.Errorf(ctx, err.Error())
return
}
http.Redirect(res, req, "/", http.StatusSeeOther)
}
f, err := os.Open("createProfile.gohtml")
if err != nil {
http.Error(res, "Server Error", http.StatusInternalServerError)
log.Errorf(ctx, err.Error())
return
}
io.Copy(res, f)
}