Home Backend Development Golang Golang implements registration and login

Golang implements registration and login

May 10, 2023 pm 03:20 PM

In the Internet era, with the continuous advancement of Internet technology and people's increasing demand for information, the registration and login functions of websites and APPs have become more and more common. This article will introduce how to use golang language to implement the registration and login function.

1. Introduction to golang

Golang is a programming language developed by Google. It has the characteristics of efficient concurrent processing, automatic garbage collection, and extremely low compilation time. It has natural Concurrency capabilities and features suitable for large-scale systems. These features make golang a very excellent server-side language. Therefore, using it to implement the registration and login function is a very good choice.

2. Environment setup

To use golang to implement the registration and login function, you first need to install the golang language in the local environment. Before installation, you need to determine the operating system type of your computer (Windows, Linux, Mac, etc.), and select the corresponding golang version to download and install.

After the installation is completed, you can enter the following command on the command line to check whether the installation is successful:

go version
Copy after login

If the version number of golang is displayed, the installation is successful.

3. Registration function implementation

  1. Create project folder

Create a folder named "login" to place this project document. Create two folders in this folder: controller and model. Among them, controller is used to place the controller code of the Web interface, and model is used to place the code of database operations.

  1. Database connection and table creation

Create a file named "db.go" in the model folder, and write the following code in it to establish a database connection :

package model

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)

const (
    USERNAME = "root"
    PASSWORD = ""
    NETWORK  = "tcp"
    SERVER   = "localhost"
    PORT     = 3306
    DATABASE = "login_system"
)

func DbConn() (db *sql.DB) {
    dbDriver := "mysql"
    dbUser := USERNAME
    dbPass := PASSWORD
    dbName := DATABASE
    db, err := sql.Open(dbDriver, dbUser+":"+dbPass+"@tcp("+SERVER+":"+strconv.Itoa(PORT)+")/"+dbName)
    if err != nil {
        fmt.Println("无法连接数据库:", err)
    } else {
        fmt.Println("成功连接数据库!")
    }
    return db
}
Copy after login

In the above code, the third-party library "go-sql-driver/mysql" is used to realize the database connection. In the code, we also need to set some basic information of the database, such as user name, password, host address, port number, database name, etc.

Next step, we need to create a file named "user.sql" to write the SQL statement to create the user table, which contains fields such as user ID, user name and password.

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `password` varchar(40) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy after login

By executing the above SQL statement, the user table can be created in the database.

  1. Write controller code

Create a file named "register.go" in the controller folder to write the controller code for the registration interface. In this file, you need to import the third-party library "net/http" and write the following code:

package controller

import (
    "crypto/md5"
    "database/sql"
    "encoding/hex"
    "fmt"
    "io/ioutil"
    "net/http"
    "server/model"
)

func Register(w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        username := r.FormValue("username")
        password := r.FormValue("password")
        // 密码加密
        h := md5.New()
        h.Write([]byte(password))
        password = hex.EncodeToString(h.Sum(nil))
        // 数据库操作
        db := model.DbConn()
        defer db.Close()
        stmt, err := db.Prepare("INSERT INTO user(username, password) VALUES (?, ?)")
        if err != nil {
            fmt.Println("SQL语句执行失败:", err)
            return
        }
        _, err = stmt.Exec(username, password)
        if err != nil {
            fmt.Println("用户注册失败:", err)
            return
        }
        fmt.Println("用户注册成功!")
    }
    // 返回页面内容
    data, err := ioutil.ReadFile("register.html")
    if err != nil {
        fmt.Println("读取文件失败:", err)
        return
    }
    w.Write([]byte(data))
}
Copy after login

In the above code, we first determine whether the request method is POST. If it is a POST request, the user name and password are obtained, the password is MD5 encrypted, and the encrypted password and user name are stored in the database.

At the end of the file, use the ioutil.ReadFile() function to read a file named "register.html" and return the content of the file to the browser. In this way, the browser can display our registration interface.

  1. Registration interface writing

Create a file named "register.html" in the login folder to write the code for the registration page. In this page, you need to use the

tag and tag to obtain the username and password information, and submit this information to the backend for processing. The specific code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
</head>
<body>
    <form action="/register" method="post">
        <p>用户名:<input type="text" name="username" /></p>
        <p>密码:<input type="password" name="password" /></p>
        <input type="submit" value="注册" />
    </form>
</body>
</html>
Copy after login

In the above code, the action attribute of the tag represents the submission address of the form, which is the URL address of the registration interface, and the method attribute represents the submission method of the form, that is, using POST method submission.

  1. Start the server

Create a file named "main.go" in the login folder to start the server. In this file, you need to import the third-party library "net/http" and write the following code:

package main

import (
    "net/http"
    "login/controller"
)

func main() {
    // 注册接口路由
    http.HandleFunc("/register", controller.Register)
    // 启动服务器
    http.ListenAndServe(":8080", nil)
}
Copy after login

In the above code, we use the http.HandleFunc() function to specify the routing address for the registration interface. After the program is started, you can access "http://localhost:8080/register" through the browser to open the registration interface.

4. Login function implementation

  1. Writing controller code

Create a file named "login.go" in the controller folder. Used to write controller code for the login interface. In this file, you need to import the third-party libraries "net/http" and "database/sql" and write the following code:

package controller

import (
    "crypto/md5"
    "database/sql"
    "encoding/hex"
    "fmt"
    "io/ioutil"
    "net/http"
    "server/model"    
)

func Login(w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        username := r.FormValue("username")
        password := r.FormValue("password")
        h := md5.New()
        h.Write([]byte(password))
        password = hex.EncodeToString(h.Sum(nil))
        // 根据用户名和密码查询数据库
        db := model.DbConn()
        defer db.Close()
        rows, err := db.Query("SELECT * FROM user WHERE username=? AND password=?", username, password)
        if err != nil {
            fmt.Println("SQL语句执行失败:", err)
            return
        }
        defer rows.Close()
        if rows.Next() {
            fmt.Println("登录成功!")
            // 返回登录成功页面
            data, err := ioutil.ReadFile("success.html")
            if err != nil {
                fmt.Println("读取文件失败:", err)
                return
            }
            w.Write([]byte(data))
        } else {
            fmt.Println("用户名或密码不正确!")
            // 返回登录失败页面
            data, err := ioutil.ReadFile("fail.html")
            if err != nil {
                fmt.Println("读取文件失败:", err)
                return
            }
            w.Write([]byte(data))
        }
    }
    // 返回登录页面
    data, err := ioutil.ReadFile("login.html")
    if err != nil {
        fmt.Println("读取文件失败:", err)
        return
    }
    w.Write([]byte(data))
}
Copy after login

In the above code, we first determine whether the request method is POST. If it is a POST request, the username and password are obtained, and the password is encrypted with MD5. Then, we query the database based on the username and password. If the query result is not empty, it means the login is successful, otherwise it means the login failed.

At the end of the file, we read two more files named "success.html" and "fail.html", which are used to represent the page content after successful and failed login respectively.

  1. Login interface writing

Create a file named "login.html" in the login folder to write the code for the login page. This page is similar to the registration page. It also needs to use the tag and tag to obtain the username and password information, and submit this information to the backend for processing. The specific code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
    <form action="/login" method="post">
        <p>用户名:<input type="text" name="username" /></p>
        <p>密码:<input type="password" name="password" /></p>
        <input type="submit" value="登录" />
    </form>
</body>
</html>
Copy after login
  1. 成功和失败页面编写

在login文件夹中创建一个名为“success.html”的文件,用来编写登录成功后的页面代码。具体代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录成功</title>
</head>
<body>
    <h1>恭喜,登录成功!</h1>
</body>
</html>
Copy after login

在login文件夹中再创建一个名为“fail.html”的文件,用来编写登录失败后的页面代码。具体代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录失败</title>
</head>
<body>
    <h1>对不起,用户名或密码错误!</h1>
</body>
</html>
Copy after login
  1. 注册接口路由修改

在“main.go”文件中,将注册接口路由的地址改为“/”即可。最终代码如下:

package main

import (
    "net/http"
    "login/controller"
)

func main() {
    // 注册接口路由
    http.HandleFunc("/", controller.Register)
    // 登录接口路由
    http.HandleFunc("/login", controller.Login)
    // 启动服务器
    http.ListenAndServe(":8080", nil)
}
Copy after login

五、总结

本文介绍了如何使用golang语言来实现注册登录功能。通过本文的学习,我们可以看到golang语言实现简洁高效、性能优越,适合用于实现服务器端开发。同时,本文也向读者展示了如何使用golang与数据库进行交互,以及如何使用golang实现Web接口的功能。希望本文能够为读者带来一些参考和启发。

The above is the detailed content of Golang implements registration and login. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1660
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang's Impact: Speed, Efficiency, and Simplicity Golang's Impact: Speed, Efficiency, and Simplicity Apr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

C   and Golang: When Performance is Crucial C and Golang: When Performance is Crucial Apr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

See all articles