/
main.go
87 lines (78 loc) · 2.23 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
86
87
package main
import (
"fmt"
"github.com/julienschmidt/httprouter"
"google.golang.org/appengine"
"google.golang.org/appengine/datastore"
"google.golang.org/appengine/log"
"html/template"
"io/ioutil"
stdlog "log"
"net/http"
)
type User struct {
Email string
UserName string
Password string
}
var tpl *template.Template
func init() {
r := httprouter.New()
http.Handle("/", r)
r.GET("/", Home)
r.GET("/form/login", Login)
r.GET("/form/signup", Signup)
r.POST("/api/checkusername", checkUserName)
r.POST("/api/createuser", createUser)
http.Handle("/favicon.ico", http.NotFoundHandler())
http.Handle("/public/", http.StripPrefix("/public", http.FileServer(http.Dir("public/"))))
tpl = template.Must(template.ParseGlob("templates/html/*.html"))
}
func Home(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
if req.URL.Path != "/" {
http.NotFound(res, req)
return
}
tpl.ExecuteTemplate(res, "home.html", nil)
}
func Login(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
tpl.ExecuteTemplate(res, "login.html", nil)
}
func Signup(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
tpl.ExecuteTemplate(res, "signup.html", nil)
}
func checkUserName(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
ctx := appengine.NewContext(req)
bs, err := ioutil.ReadAll(req.Body)
sbs := string(bs)
stdlog.Println("REQUEST BODY: ", sbs)
q, err := datastore.NewQuery("Users").Filter("UserName=", sbs).Count(ctx)
stdlog.Println("ERR: ", err)
stdlog.Println("QUANTITY: ", q)
if err != nil {
fmt.Fprint(res, "false")
return
}
if q >= 1 {
fmt.Fprint(res, "true")
} else {
fmt.Fprint(res, "false")
}
}
func createUser(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
ctx := appengine.NewContext(req)
NewUser := User{
Email: req.FormValue("email"),
UserName: req.FormValue("userName"),
Password: req.FormValue("password"),
}
key := datastore.NewIncompleteKey(ctx, "Users", nil)
key, err := datastore.Put(ctx, key, &NewUser)
// this is the only error checking I added; any others on this page needed?
if err != nil {
log.Errorf(ctx, "error adding todo: %v", err)
http.Error(res, err.Error(), 500)
return
}
http.Redirect(res, req, "/", 302)
}