Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func Signup(w http.ResponseWriter, r *http.Request) {
- if r.Method == "GET" {
- // send signup form
- templates["signup"].Execute(w, nil)
- } else if r.Method == "POST" {
- // parse form data and validate email and compare passwords
- vars := mux.Vars(r)
- email := vars["email"]
- username := vars["username"]
- password := vars["password"]
- confirm_password := vars["confirm_password"]
- if password != confirm_password {
- // handle error 'password must match'
- fmt.Fprintln(w, "Password and Confirm Password MUST match!")
- // return
- } else if validateEmail(email) { // validate email is proper
- fmt.Fprintln(w, email+" is not a valid email.")
- }
- // if passwords and email good, insert data into db and redirect to index
- var user string
- err := db.QueryRow("SELECT username FROM users WHERE username=?", username).Scan(&user)
- switch {
- // Username is available
- case err == sql.ErrNoRows:
- hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
- if err != nil {
- http.Error(w, "Server error, unable to hash your password.", 500)
- return
- }
- _, err = db.Exec("INSERT INTO users(username, email, password) VALUES(?, ?)", username, email, hashedPassword)
- if err != nil {
- http.Error(w, "Server error, unable to create your account.", 500)
- return
- }
- w.Write([]byte("User created!"))
- return
- case err != nil:
- http.Error(w, "Server error, unable to create your account. some errororsrosr", 500)
- return
- default:
- http.Redirect(w, r, "/", 301)
- }
- } else {
- // not POST or GET then WTF?!?
- http.Error(w, "Wut O.o", http.StatusMethodNotAllowed)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement