-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
main.go
executable file
·69 lines (59 loc) · 1.67 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
package main
import (
"encoding/json"
"html/template"
"net/http"
"github.com/julienschmidt/httprouter"
"google.golang.org/appengine"
"google.golang.org/appengine/datastore"
"google.golang.org/appengine/user"
)
type Profile struct {
Email string
FirstName string
LastName string
Age int
}
func init() {
router := httprouter.New()
router.GET("/", showIndex)
router.GET("/profile", showProfile)
router.GET("/api/profile", getAPIProfile)
router.POST("/api/profile", updateAPIProfile)
http.Handle("/", router)
}
func getAPIProfile(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
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 != nil {
profile.Email = u.Email
}
json.NewEncoder(res).Encode(profile)
}
func updateAPIProfile(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
var profile Profile
json.NewDecoder(req.Body).Decode(&profile)
ctx := appengine.NewContext(req)
u := user.Current(ctx)
key := datastore.NewKey(ctx, "Profile", u.Email, 0, nil)
_, err := datastore.Put(ctx, key, &profile)
if err != nil {
http.Error(res, err.Error(), 500)
}
}
func showIndex(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
http.Redirect(res, req, "/profile", 302)
}
func showProfile(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
tpl, err := template.ParseFiles("templates/templates.gohtml")
if err != nil {
panic(err)
}
err = tpl.ExecuteTemplate(res, "templates.gohtml", nil)
if err != nil {
http.Error(res, err.Error(), 500)
}
}