Home  >  Article  >  Backend Development  >  From entry to proficiency: Mastering the go-zero framework

From entry to proficiency: Mastering the go-zero framework

WBOY
WBOYOriginal
2023-06-23 11:37:372202browse

Go-zero is an excellent Go language framework that provides a complete set of solutions, including RPC, caching, scheduled tasks and other functions. In fact, it is very simple to build a high-performance service using go-zero, and you can even go from beginner to proficient in a few hours.

This article aims to introduce the process of building high-performance services using the go-zero framework and help readers quickly grasp the core concepts of the framework.

1. Installation and configuration

Before we start using go-zero, we need to install it and configure some necessary environments.

1. Installation

Installing go-zero is very simple, just execute the following command:

$ go get -u github.com/tal-tech/go-zero

This will automatically download the latest version of go-zero from GitHub . However, it should be noted that it is recommended to use Go 1.13 and above.

2. Configuration

Before using go-zero, we need to configure some necessary environments for it. Specifically, we need to install the goctl command line tool in order to use go-zero to create services.

$ GO111MODULE=on go get -u github.com/tal-tech/go-zero/tools/goctl

3. Create a project

Next, we need to use goctl to create a new project. We assume that the project is named blog and can be created with the following command:

$ mkdir blog
$ cd blog
$ go mod init blog
$ goctl api new blog

The above command will create a new API project and generate some necessary files and directories.

2. Create a service

Next, we can use go-zero to create a new service. We assume that the service name is user-service, which can be created through the following steps:

1. Generate service

Use goctl to generate the service code of user-service:

$ goctl api go -api user.api -dir .

The above command A user directory will be generated in the current directory, containing a file named user.go, which contains the service code of user-service.

2. Implement handler

We also need to implement specific business logic, which is handler.

First, we need to create a new directory named handler in the user directory and create a file named userhandler.go in it. This file will contain our handler code.

userhandler.go code is as follows:

package handler

import (
    "net/http"

    "github.com/tal-tech/go-zero/rest/httpx"
    "blog/service/user/api/internal/logic"
    "blog/service/user/api/internal/svc"
)

func userHandler(ctx *svc.ServiceContext) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        req, err := httpx.NewRequest(r)
        if err != nil {
            httpx.WriteError(w, err)
            return
        }

        l := logic.NewUserLogic(r.Context(), ctx)
        resp, err := l.GetUser(req)
        if err != nil {
            httpx.WriteError(w, err)
            return
        }

        httpx.WriteJson(w, resp)
    }
}

The above code uses the rest/httpx package provided by go-zero, which provides some convenient functions, such as NewRequest, WriteError and WriteJSON, etc. Simplified HTTP service writing process.

3. Register handler

Now we need to register the above handler program into the service.

In the init method in the user.go file, add the following code:

func (s *Service) InitHandlers() {
    s.UserHandler = http.HandlerFunc(handler.UserHandler(s.Context))
}

The above code registers the userHandler function as an HTTP service. We can access this by defining routes in the API file. Serve.

3. Create a template

We can generate a new go-zero API through goctl create api, which will automatically create a folder containing some initialization configurations. We can add our own controller and service in it according to goctl's requirements.

Here we create a template application to better learn to read the source code of go-zero. The application will contain a CRUD example demonstrating how to use go-zero's common features.

1. Generate template

We can use goctl to generate a template application to better learn the source code of go-zero.

$ goctl api template -o app.go

The above command will create a file named app.go which contains all the source code of the template application.

2. Implement data access

We assume that MySQL is used for data storage. Before starting, MySQL needs to be installed and configured. On this basis, we can use go-sql provided by go-zero to build the database access layer.

Specifically, we can use goctl to generate the data access layer code:

$ goctl model mysql datasource "root:123456@tcp(127.0.0.1:3306)/test" -table user -dir .

The above command will generate a userModel.go file, which contains the user data model for data access.

3. Implement business logic

Next, we need to implement the business logic and use it in conjunction with the data access layer. Specifically, we can create a file called userLogic.go that contains business logic for user management.

userLogic.go code is as follows:

package logic

import (
    "context"
    "github.com/tal-tech/go-zero/core/logx"
    "github.com/tal-tech/go-zero/core/stores/sqlx"
    "blog/service/user/model"
    "blog/service/user/api/internal/svc"
    "blog/service/user/api/internal/types"
)

type UserLogic struct {
    ctx context.Context
    svcCtx *svc.ServiceContext
    logx.Logger
}

func NewUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) UserLogic {
    return UserLogic{
        ctx: ctx,
        svcCtx: svcCtx,
        Logger: logx.WithContext(ctx),
    }
}

func (l *UserLogic) GetUser(req types.GetUserRequest) (*types.GetUserResponse, error) {
    //Todo
}

In the above code, we introduced the sqlx, stores and logx packages, where sqlx is part of the go-zero framework and is specifically used for database operations . stores is the data storage layer of the go-zero framework. The logx package is a logging library provided by the go-zero framework, which can help us record important events.

4. Integrate ETCD, etc.

Using the go-zero framework, we can easily integrate some commonly used tools and services, such as ETCD, Redis, ZooKeeper, etc. Specifically, we can import the relevant libraries provided by go-zero in the code and configure the relevant information in the configuration file.

The following are some commonly used integration methods:

1. Integrate ETCD

First, add the following information in the configuration file:

[etcd]
host = "localhost:2379"

Then, in To use etcd code, use the clientv3.New function to create a new etcd client.

import (
    "go.etcd.io/etcd/clientv3"
)

client, err := clientv3.New(clientv3.Config{
    Endpoints:   []string{"localhost:2379"},
    DialTimeout: 5 * time.Second,
})
if err != nil {
    panic(err)
}

The above code will create an ETCD client named client, which will use localhost:2379 as the address of the ETCD server.

2. Integrate Redis

To use Redis, we need to add the following information to the configuration file:

[redis]
host = "localhost:6379"
password = ""
db = 0

Then, in the code where you want to use Redis, use redis. The NewClient function creates a new Redis client.

import (
    "github.com/go-redis/redis"
)

client := redis.NewClient(&redis.Options{
    Addr:     "localhost:6379",
    Password: "", // no password set
    DB:       0,  // use default DB
})

The above code will create a new Redis client, which will use localhost:6379 as the Redis server address, no password, and use the default DB.

3.Integrate ZooKeeper

要使用ZooKeeper,我们需要在配置文件中添加以下信息:

[zookeeper]
host = "localhost:2181"

然后,在要使用ZooKeeper的代码中,使用zk.Connect函数创建一个新的ZooKeeper客户端。

import (
    "github.com/samuel/go-zookeeper/zk"
    "time"
)

conn, _, err := zk.Connect([]string{"localhost:2181"}, time.Second*5)
if err != nil {
    panic(err)
}

上述代码将创建一个名为conn的ZooKeeper客户端,它将使用localhost:2181作为ZooKeeper服务器的地址。

五、总结

到目前为止,我们已经深入了解了go-zero框架,并学到了如何使用它来构建高性能服务。

总结一下,要使用go-zero,请先安装和配置相关环境,然后创建一个新的项目,通过goctl命令行工具自动生成模板代码和配置文件。

接着,可以使用go-zero提供的各种功能和服务来逐步完善和扩展我们的应用程序,如集成数据库、ETCD、Redis等。

将go-zero框架用于您的下一个项目吧,它将使您能够构建出更加灵活、高效和可靠的服务!

The above is the detailed content of From entry to proficiency: Mastering the go-zero framework. 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