Building Login and Register Application with Go

Cihan Ozhan
4 min readNov 8, 2021

--

Building Login and Register Application with Go

I wrote this code in 2016 but re-shared it for newbies.

Basic knowledges we need to know to develop web app with Go; Login and Register!

For this reason, in this article, we will prepare examples for login and register.

Section 1:

To do list;

  • Form data process
  • Login example
  • Register example

helpers/StringHelpers.go

package helpers

func IsEmpty(data string) bool {
if len(data) == 0 {
return true
} else {
return false
}
}

main.go

package main

import (
"fmt"
"net/http"

h "helpers"
)

func main() {

uName, email, pwd, pwdConfirm := "", "", "", ""

mux := http.NewServeMux()

// Signup
mux.HandleFunc("/signup", func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()

/*
// Available for testing.
for key, value := range r.Form {
fmt.Printf("%s = %s\n", key, value)
}
*/

// Data from the form
uName = r.FormValue("username")
// Data from the form
email = r.FormValue("email")
// Data from the form
pwd = r.FormValue("password")
// Data from the form
pwdConfirm = r.FormValue("confirm")

// Empty data checking
uNameCheck := h.IsEmpty(uName)
emailCheck := h.IsEmpty(email)
pwdCheck := h.IsEmpty(pwd)
pwdConfirmCheck := h.IsEmpty(pwdConfirm)

if uNameCheck || emailCheck || pwdCheck || pwdConfirmCheck {
fmt.Fprintf(w, "ErrorCode is -10 : There is empty data.")
return
}

if pwd == pwdConfirm {
// Save to database (username, email and password)
fmt.Fprintln(w, "Registration successful.")
} else {
fmt.Fprintln(w, "Password information must be the same.")
}
})

// Login
mux.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()

email = r.FormValue("email") // Data from the form
pwd = r.FormValue("password") // Data from the form

// Empty data checking
emailCheck := h.IsEmpty(email)
pwdCheck := h.IsEmpty(pwd)

if emailCheck || pwdCheck {
fmt.Fprintf(w, "ErrorCode is -10 : There is empty data.")
return
}

dbPwd := "1234!*." // DB simulation
dbEmail := "cihan.ozhan@hotmail.com" // DB simulation

if email == dbEmail && pwd == dbPwd {
fmt.Fprintln(w, "Login succesful!")
} else {
fmt.Fprintln(w, "Login failed!")
}
})

http.ListenAndServe(":8080", mux)
}

Section 2 : User login, register and cookie

To do list;

  • Form data process
  • Login example
  • Register example

helpers/FileHelper.go

package helpers

import "io/ioutil"

func LoadFile(fileName string) (string, error) {
bytes, err := ioutil.ReadFile(fileName)
if err != nil {
return "", err
}
return string(bytes), nil
}

helpers/StringHelper.go

package helpers

func IsEmpty(data string) bool {
if len(data) <= 0 {
return true
} else {
return false
}
}

data/UserData.go

package data

func UserIsValid(uName, pwd string) bool {
// DB simulation
_uName, _pwd, _isValid := "cihanozhan", "1234!*.", false

if uName == _uName && pwd == _pwd {
_isValid = true
} else {
_isValid = false
}

return _isValid
}

common/Handlers.go

package handlers

import (
"fmt"
"net/http"

"helpers"
"data"
"github.com/gorilla/securecookie"
)

var cookieHandler = securecookie.New(
securecookie.GenerateRandomKey(64),
securecookie.GenerateRandomKey(32))

// Handlers

// for GET
func LoginPageHandler(response http.ResponseWriter, request *http.Request) {
var body, _ = helpers.LoadFile("templates/login.html")
fmt.Fprintf(response, body)
}

// for POST
func LoginHandler(response http.ResponseWriter, request *http.Request) {
name := request.FormValue("name")
pass := request.FormValue("password")
redirectTarget := "/"
if !helpers.IsEmpty(name) && !helpers.IsEmpty(pass) {
// Database check for user data!
_userIsValid := data.UserIsValid(name, pass)

if _userIsValid {
SetCookie(name, response)
redirectTarget = "/index"
} else {
redirectTarget = "/register"
}
}
http.Redirect(response, request, redirectTarget, 302)
}

// for GET
func RegisterPageHandler(response http.ResponseWriter, request *http.Request) {
var body, _ = helpers.LoadFile("templates/register.html")
fmt.Fprintf(response, body)
}

// for POST
func RegisterHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()

uName := r.FormValue("username")
email := r.FormValue("email")
pwd := r.FormValue("password")
confirmPwd := r.FormValue("confirmPassword")

_uName, _email, _pwd, _confirmPwd := false, false, false, false
_uName = !helpers.IsEmpty(uName)
_email = !helpers.IsEmpty(email)
_pwd = !helpers.IsEmpty(pwd)
_confirmPwd = !helpers.IsEmpty(confirmPwd)

if _uName && _email && _pwd && _confirmPwd {
fmt.Fprintln(w, "Username for Register : ", uName)
fmt.Fprintln(w, "Email for Register : ", email)
fmt.Fprintln(w, "Password for Register : ", pwd)
fmt.Fprintln(w, "ConfirmPassword for Register : ", confirmPwd)
} else {
fmt.Fprintln(w, "This fields can not be blank!")
}
}

// for GET
func IndexPageHandler(response http.ResponseWriter, request *http.Request) {
userName := GetUserName(request)
if !helpers.IsEmpty(userName) {
var indexBody, _ = helpers.LoadFile("templates/index.html")
fmt.Fprintf(response, indexBody, userName)
} else {
http.Redirect(response, request, "/", 302)
}
}

// for POST
func LogoutHandler(response http.ResponseWriter, request *http.Request) {
ClearCookie(response)
http.Redirect(response, request, "/", 302)
}

// Cookie

func SetCookie(userName string, response http.ResponseWriter) {
value := map[string]string{
"name": userName,
}
if encoded, err := cookieHandler.Encode("cookie", value); err == nil {
cookie := &http.Cookie{
Name: "cookie",
Value: encoded,
Path: "/",
}
http.SetCookie(response, cookie)
}
}

func ClearCookie(response http.ResponseWriter) {
cookie := &http.Cookie{
Name: "cookie",
Value: "",
Path: "/",
MaxAge: -1,
}
http.SetCookie(response, cookie)
}

func GetUserName(request *http.Request) (userName string) {
if cookie, err := request.Cookie("cookie"); err == nil {
cookieValue := make(map[string]string)
if err = cookieHandler.Decode("cookie", cookie.Value, &cookieValue); err == nil {
userName = cookieValue["name"]
}
}
return userName
}

main.go

package main

import (
"net/http"

"github.com/gorilla/mux"

"common"
)

var router = mux.NewRouter()

func main() {
router.HandleFunc("/", common.LoginPageHandler) // GET

router.HandleFunc("/index", common.IndexPageHandler) // GET
router.HandleFunc("/login", common.LoginHandler).Methods("POST")

router.HandleFunc("/register", common.RegisterPageHandler).Methods("GET")
router.HandleFunc("/register", common.RegisterHandler).Methods("POST")

router.HandleFunc("/logout", common.LogoutHandler).Methods("POST")

http.Handle("/", router)
http.ListenAndServe(":8080", nil)
}

Run it!

go run main.go

--

--

No responses yet