Adding Registration Functionality

In this section, we'll add functionality to allow a user to register in our application with a username and password. To do this, we'll need to manage users and allow users to register.

The code for this section will be organized as follows:

  • models.user.go will contain the user model,
  • handlers.user.go will contain the request handlers,
  • routes.go will be updated with the new routes,
  • templates/register.html will show the registration form,
  • templates/menu.html will be updated with a Register menu, and
  • templates/login-successful will be shown after successful registration.

Let's begin by creating a skeleton for the models.user.go and handlers.user.go files so that we can start writing tests.

In models.user.go, we will define:

  • A user struct to hold a user's details,
  • A userList array to hold the list of users,
  • A registerNewUser function to register a new user, and
  • A isUsernameAvailable function to check if username is available.

With these additions, the models.user.go file should contain the following:

// models.user.go

package main

import "errors"

type user struct {
    Username string `json:"username"`
    Password string `json:"-"`
}

var userList = []user{
    user{Username: "user1", Password: "pass1"},
    user{Username: "user2", Password: "pass2"},
    user{Username: "user3", Password: "pass3"},
}

func registerNewUser(username, password string) (*user, error) {
    return nil, errors.New("placeholder error")
}

func isUsernameAvailable(username string) bool {
    return false
}

In handlers.user.go, we will define a showRegistrationPage handler to show the registration page and a register handler to handle the registration request.

With these additions, the handlers.user.go file should contain the following:

// handlers.user.go

package main

import "github.com/gin-gonic/gin"

func showRegistrationPage(c *gin.Context) {
}

func register(c *gin.Context) {
}

results matching ""

    No results matching ""