[Ultimate giant pit] golang + vue development diary [three], the login screen production (b)

EDITORIAL

In this issue is to undertake a period already done the login screen to write, but the main issue is golang, you may need to familiarize yourself with the basic grammatical structure: rookie tutorial . So easy to start, naturally herein, this is also a direct combat based. The need to rely on mysql, this must be installed, redis best to also install what the future will be used.

Start a go project

Here I'm going to go start a web application, then many people will own words from the beginning, but it was a little trouble, in fact, many Internet heavyweights wrote some scaffolding, and here I intend to directly bydmm singo project chiefs to develop, can B space station to see his series of tutorials: personal space bydmm of .

So, the first on github project to get down to:

git clone https://github.com/Gourouting/singo.git

Then the project folder directory renamed themselves the name of the project, it is to singo the folder name to change, and then import all the files inside the corresponding need to change the name of your project singo.

We can take a look at the way the project structure, explain:

The name of the folder are obviously exposed intent here is my intention to temporarily not one to talk, because I'm going to say something here go all projects should have the basic thing is main.go. If you learned programming all understand that there is one and only entry of a program, so this entry is main.go, and he only needs to satisfy his package is main, and there is a func main () will be able to:

package main

func main() {
}

Project Environment Configuration

The scaffolding of his environment configuration using .env to configure, and he also has a .env exmaple, if you want to know where to look you can achieve the conf folder below conf.go, is through .env set the environment variable in the project, then get in conf.go only, so you modify the file name and the MYSQL_DSN can be modified to your own, you do not know if the DSN, you can refer to the following format to write:

username: password @ protocol (address) / dbname param value =?
an example, because the default localhost: 3306, you can not write the protocol field
root:? 123456 @ / ysyh charset = utf8 & parseTime = True & loc = Local

go mod how to use

go mod in here is the package manager, in the first article should have a good job goproxy and go111module, the package manager in today's very fast hardware version, you only need to do two things that can be done, in order to demonstrate that we first the original project go.mod and go.sum to delete, and then enter the shell:

go mod init your_projectname

So you somehow go mod, you then he will automatically detect your missing dependencies when you run the project, and the installation, you can just give it a try:

go run main.go

Originally go.mod file you have only one line statement more than a bunch of dependent and can run the project.

routing

The first thing is to do the back-end receives the request, only you can accept the request and sent him to the address corresponding to the next operation only, so we see from the route. For routing gin, the official has been written very clearly in the project which is router.go under the server, the following are a few key codes

func NewRouter() *gin.Engine {
    r := gin.Default()

    r.Use(middleware.Cors())

    v1 := r.Group("/api/v1")
    {
        v1.POST("ping", api.Ping)
        auth := v1.Group("")
        auth.Use(middleware.AuthRequired())
        {
            auth.GET("user/me", api.UserMe)
                }
        }
}

I only interception of a few points of knowledge, first gin.Default () is a routing, you just r.Run ( ": port") can be executed directly on the route to the port.

Next there is a r.Use, this is the meaning of middleware, middleware is actually a method to your route before, and he will do this inside the method, such as the example of Cors, because almost all of my requests have to do Cors, so I can not write in it every method again this code, so we put it inside the middleware save trouble. You can look at the gin of middlerware format:

import(
    "github.com/gin-contrib/cors"
)
func Cors() gin.HandlerFunc {
    config := cors.DefaultConfig()
        return cors.New(config)
}

Cors take as an example, just take a gin.HandlerFunc incoming Use methods which can be achieved middleware registration.

Group method, in fact, is to put his Group following address plus the period of address, such as the example, v1 way to do the following post, his address is / api / v1 / ping, three api.ping call this method. In fact, just look at this feature is also a general feeling, but you can look at the example below auth, he directly Use the auth below, made a login authentication, so there is a middlerware in auth following address, no landing no way to access . Thus, after the group members to the packets may add middlerware, so that the code amount can save a lot.

Handler

After routing it will reach the function you want to process this request, I take a direct registration as an example to illustrate.

func UserRegister(c *gin.Context) {
    var service service.UserRegisterService
    if err := c.ShouldBind(&service); err == nil {
        res := service.Register()
        c.JSON(200, res)
    } else {
        c.JSON(200, ErrorResponse(err))
    }
}

This is the registration processing function, but this is the scaffolding made package, but already there is a soul. First, there are functions that can come parameter is a value gin.Context pointer. Context context name suggests, in fact, requested cookie, headers, content and the like. So the information we have requested from the inside to get.

After this there c.ShouldBind (& service), this means that you can make a request to verify the content, if they meet the service this strcut it, he'll tell you the contents of the request is not a problem, where you can take a look at this struct of writing

type UserRegisterService struct {
    Email           string `form:"email" json:"email" binding:"required,email"`
    UserName        string `form:"user_name" json:"user_name" binding:"required,min=5,max=30"`
    Password        string `form:"password" json:"password" binding:"required,min=8,max=40"`
    PasswordConfirm string `form:"password_confirm" json:"password_confirm" binding:"required,min=8,max=40"`
}

In addition to the last name field you should be able to able to understand. Finally, there is the face of paragraphs, gin can be read there, and according to the content here to judge whether incoming parameter in question, can look Email this example, he asked preceding paragraph may be submitted in form or json submit his corresponding field is email, and be followed by a binding, this is a validation rule, required on his behalf must be present, he is the representative of the second email is a text email format.

Finally, let's deal with the end result will return, here you can directly c.JSON returned to json format.

Database operations

Back-end operations inevitably interacts with the database, so the database operations here is very important, here we used a database called the gorm, can look gorm official documents . But gorm only supports mysql, PostgreSQL and Sqlite3, other databases may take other orm. Here you can see the basic operation of the database init.go in model

func Database(connString string) {
    db, err := gorm.Open("mysql", connString)
    if err != nil {
        util.Log().Panic("连接数据库不成功", err)
    }
    //设置连接池
    //空闲
    db.DB().SetMaxIdleConns(50)
    //打开
    db.DB().SetMaxOpenConns(100)
    //超时
    db.DB().SetConnMaxLifetime(time.Second * 30)

    migration()
}

I have here is the important link with the database code out, and here I have not a single case of use posted. First, how to link the database is gorm.Open get away, then the first parameter is the database type, the second is the DSN, DSN already talked about above.

After what we have to set some parameters, the above is also written very clearly, and finally there is a migration, this is a very powerful feature gorm, he can go automatically generate tables and modify table structure. In fact, DB.AutoMigrate this method, every time you run, he will go to the inside of the struct added to the database, such as tables where the user is automatically migrated with the following stcut:

// User 用户模型
type User struct {
    gorm.Model
    UserName       string
    PasswordDigest string
    Email       string
    Status         string
    Avatar         string `gorm:"size:1000"`
}

There's gorm.Model is such that there may be related to the content of the soft-deleted gorm, it is recommended that you add gorm.Model in any table structure:

type Model struct {
    ID        uint `gorm:"primary_key"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time `sql:"index"`
}

Front-end request

We have the most basic logic to understand the back-end, although not get ~ ~ implementation logic. But we made a request to the backend Vue how? You may know how people ought to know ajax, and in which the words we used Vue is axios, is based on the mechanism of Promise, first of all you can install it.

npm install axios

And then in main.js inside plus (where the second line is to prevent Cors do when problems):

import axios from 'axios';
= true axios.defaults.withCredentials
Vue.prototype. $ axios = axios;

Then we do in our project file can request:

this.$axios.get("http://127.0.0.1:3000/api/v1/user/me").then((res) => {
    //todo
}).catch(err => {
    //todo
}).finally(() => {
})

If the request is a post on the back of the parameters of the request to add. After this request, if correct, would be to then inside, the result is to use a variable to accept. There is a problem you can catch the error, the last can also be used finally, regardless of the success of this function will do.

Guess you like

Origin www.cnblogs.com/segredo/p/11663224.html