Home >Backend Development >Golang >How to use Go language to write the user registration module in the door-to-door cooking system?

How to use Go language to write the user registration module in the door-to-door cooking system?

WBOY
WBOYOriginal
2023-11-01 17:13:59500browse

How to use Go language to write the user registration module in the door-to-door cooking system?

This article will introduce how to use Go language to write a user registration module for a door-to-door cooking system. We will cover the basic business process of user registration and provide code examples.

1. Requirements Analysis

First of all, we need to understand the basic steps that users need to complete in our system. The user registration module needs to meet the following requirements:

  1. Users can enter username, password and mobile phone number to register an account
  2. Username, password and mobile phone number need to be verified when registering Legality
  3. After the user successfully registers, the system needs to automatically send a text message notification and jump to the login page

2. Technology selection

Go language has excellent performance, A programming language with simple syntax is currently widely used in server-side development, network programming and other fields. Therefore, we choose to use Go language to write this user registration module.

At the same time, we also need to use the API provided by the SMS service provider to implement the SMS notification function. In this article, we will use Alibaba Cloud SMS Service to complete this task.

3. Database design

Before we start writing code, we need to design a data table to manage user information. We can use MySQL database to store user data.

Here we design a data table named users to save user information. The table structure is as follows:

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  `username` varchar(20) NOT NULL COMMENT '用户名',
  `password` varchar(32) NOT NULL COMMENT '密码',
  `phone` varchar(20) NOT NULL COMMENT '手机号码',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`),
  UNIQUE KEY `phone` (`phone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';

Through the above SQL statement, we create a data table named users data table, and defines the fields that need to be stored in the data table.

4. Write code

  1. Introduce dependencies

We use the github.com/gin-gonic/gin framework, which It is a lightweight web framework that can help us quickly build HTTP applications.

At the same time, we use github.com/aliyun/alibaba-cloud-sdk-go/sdk to call the Alibaba Cloud SMS service API.

Before we start writing code, we need to add dependency information in the go.mod file:

require (
    github.com/gin-gonic/gin v1.6.3
    github.com/aliyun/alibaba-cloud-sdk-go/sdk v1.0.0
)
  1. Write routing function

We use HTTP POST requests to submit user registration information. In the router.go file, we can define a /register route and bind it to a registration function.

package main

import (
    "net/http"

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

func main() {
    router := gin.Default()

    // 绑定注册函数
    router.POST("/register", registerHandler)

    router.Run()
}

func registerHandler(c *gin.Context) {
    // TODO
}
  1. Processing request data

In the registerHandler function, we need to get the user name, password and mobile phone number from the request parameters, and authenticating.

func registerHandler(c *gin.Context) {
    // 获取请求参数
    username := c.PostForm("username")
    password := c.PostForm("password")
    phone := c.PostForm("phone")

    // 参数校验
    if username == "" || password == "" || phone == "" {
        c.JSON(http.StatusBadRequest, gin.H{
            "code":    http.StatusBadRequest,
            "message": "请求参数错误",
        })
        return
    }

    // TODO: 更多参数校验操作
}
  1. Check whether the user already exists

Before inserting data into the database, we need to check whether the user name and mobile phone number have been registered. If it has been registered, an error message will be returned.

func registerHandler(c *gin.Context) {
    // 获取请求参数
    username := c.PostForm("username")
    password := c.PostForm("password")
    phone := c.PostForm("phone")

    // 参数校验
    if username == "" || password == "" || phone == "" {
        c.JSON(http.StatusBadRequest, gin.H{
            "code":    http.StatusBadRequest,
            "message": "请求参数错误",
        })
        return
    }

    // 检查用户是否已存在
    var user User
    if err := db.Where("username = ?", username).Or("phone = ?", phone).First(&user).Error; err == nil {
        c.JSON(http.StatusBadRequest, gin.H{
            "code":    http.StatusBadRequest,
            "message": "用户名或手机号已被注册",
        })
        return
    }

    // TODO: 插入用户数据并发送短信通知
}
  1. Insert user data and send SMS notification

Finally, we need to insert user data into the database and send SMS notification through Alibaba Cloud SMS API.

import "github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"

// 插入用户数据并发送短信通知
user := User{
    Username: username,
    Password: utils.MD5(password),
    Phone:    phone,
}
if err := db.Create(&user).Error; err != nil {
    c.JSON(http.StatusInternalServerError, gin.H{
        "code":    http.StatusInternalServerError,
        "message": "系统错误",
    })
    return
}

// 调用阿里云短信API发送短信通知
client, _ := dysmsapi.NewClientWithAccessKey("cn-hangzhou", "AKID", "AKSECRET")
request := dysmsapi.CreateSendSmsRequest()
request.Scheme = "https"
request.PhoneNumbers = phone
request.SignName = "签名"
request.TemplateCode = "模板ID"
request.TemplateParam = `{"code": "123456"}`
response, err := client.SendSms(request)
if err != nil || !response.IsSuccess() {
    c.JSON(http.StatusInternalServerError, gin.H{
        "code":    http.StatusInternalServerError,
        "message": "短信发送失败",
    })
    return
}

c.JSON(http.StatusOK, gin.H{
    "code":    http.StatusOK,
    "message": "注册成功",
})

At this point, we have completed the writing of the user registration module, which can be tested through tools such as Postman.

5. Summary

In this article, we use Go language to write a user registration module for the door-to-door cooking system. By using the Alibaba Cloud SMS API to implement the SMS notification function and using the MySQL database to manage user data, a complete user registration system can be implemented. If you are interested in Go language development, you might as well try using this project for more in-depth learning.

The above is the detailed content of How to use Go language to write the user registration module in the door-to-door cooking system?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn