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.gowill contain the user model,handlers.user.gowill contain the request handlers,routes.gowill be updated with the new routes,templates/register.htmlwill show the registration form,templates/menu.htmlwill be updated with aRegistermenu, andtemplates/login-successfulwill 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
userstruct to hold a user's details, - A
userListarray to hold the list of users, - A
registerNewUserfunction to register a new user, and - A
isUsernameAvailablefunction 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) {
}