Home  >  Article  >  Backend Development  >  Use go-zero+Vue.js to implement front-end and back-end separated API service design

Use go-zero+Vue.js to implement front-end and back-end separated API service design

WBOY
WBOYOriginal
2023-06-23 08:46:291160browse

In today's rapidly developing Internet era, front-end and back-end separated API service design has become a very popular design idea. Using this design idea, we can develop front-end code and back-end code separately, thereby achieving more efficient development and better system maintainability. This article will introduce how to implement front-end and back-end separated API service design by using go-zero and Vue.js.

1. Advantages of front-end and back-end separated API service design

The advantages of front-end and front-end separated API service design mainly include the following aspects:

  1. Development efficiency Higher

Using the front-end and back-end separated API service design can carry out the development of the front-end and the back-end in parallel, without having to wait for the other party's development to be completed before proceeding to the next step of development work. This can shorten the development cycle and improve development efficiency.

  1. Achieve cross-platform

Using the front-end and back-end separated API service design, the front-end and back-end can be deployed on different servers respectively to achieve cross-platform. This can better adapt to different needs and scenarios.

  1. Improve system maintainability

Using the front-end and back-end separated API service design can separate the front-end and back-end code, making maintenance easier. Front-end and back-end developers can be responsible for their own code maintenance respectively, which can reduce the difficulty and risk of software maintenance.

2. Introduction to go-zero

go-zero is a high-performance microservice development framework that provides a wealth of functions and plug-ins to quickly build high-performance microservice applications. . go-zero supports multiple transport protocols, including HTTP, gRPC, and TCP. It also provides a variety of middleware, including ETCD, Redis, MySQL, etc., which can easily implement functions such as service registration, configuration center and storage.

3. Introduction to Vue.js

Vue.js is a very popular front-end JavaScript framework. It adopts the MVVM (Model-View-ViewModel) architectural pattern and provides a wealth of Components and plug-ins can quickly build efficient front-end applications. Vue.js follows a data-driven development model, which can reduce the number of DOM operations and improve the performance of front-end applications.

4. Use go-zero and Vue.js to implement front-end and back-end separated API service design

First, we need to use go-zero to build the back-end service. go-zero provides a wealth of plug-ins and middleware, and we can quickly build high-performance API services. Next, we use Vue.js to build the front-end application and call the back-end API service through the HTTP protocol to achieve a front-end and back-end separated API service design.

Below we take a simple student information management system as an example to demonstrate how to use go-zero and Vue.js to implement front-end and back-end separated API service design.

  1. Back-end code

We first write the back-end code to implement API services through the go-zero framework. Create a student directory in the root directory of the project, and then create a student.api file in the directory to define the API interface for student information:

type (
    Student struct {
        Id       int64  `db:"id"`
        Name     string `db:"name"`
        Age      int    `db:"age"`
        Class    string `db:"class"`
        CreateAt string `db:"create_at"`
        UpdateAt string `db:"update_at"`
    }
    
    ListRequest struct {
        Offset int `form:"offset"`
        Limit  int `form:"limit"`
    }
)

type StudentApi interface {
    AddStudent(ctx context.Context, req types.AddStudentRequest) (*types.StudentReply, error)
    DeleteStudent(ctx context.Context, req types.DeleteStudentRequest) (*types.StudentReply, error)
    UpdateStudent(ctx context.Context, req types.UpdateStudentRequest) (*types.StudentReply, error)
    GetStudent(ctx context.Context, req types.GetStudentRequest) (*types.StudentReply, error)
    ListStudent(ctx context.Context, req types.ListStudentRequest) (*types.StudentListReply, error)
}

We have defined 5 API interfaces in this file, respectively. Used to add, delete, modify, query and list student information. Next, we create a service.go file in the student directory to implement the service interface of student information:

type StudentService struct {
    models.SvcCtx
}

func NewStudentService(ctx *models.ServiceContext) *StudentService {
    return &StudentService{
        SvcCtx: ctx,
    }
}

func (s *StudentService) AddStudent(ctx context.Context, req types.AddStudentRequest) (*types.StudentReply, error) {
    student := &model.Student{
        Name:   req.Name,
        Age:    req.Age,
        Class:  req.Class,
        CreateAt: time.Now().Format("2006-01-02 15:04:05"),
        UpdateAt: time.Now().Format("2006-01-02 15:04:05"),
    }

    id, err := s.Model.Insert(student)
    if err != nil {
        return nil, err
    }

    return &types.StudentReply{
        Id: id,
    }, nil
}

func (s *StudentService) DeleteStudent(ctx context.Context, req types.DeleteStudentRequest) (*types.StudentReply, error) {
    affected, err := s.Model.Delete(&model.Student{
        Id: req.Id,
    })
    if err != nil {
        return nil, err
    }

    return &types.StudentReply{
        Affected: affected,
    }, nil
}

func (s *StudentService) UpdateStudent(ctx context.Context, req types.UpdateStudentRequest) (*types.StudentReply, error) {
    student := &model.Student{
        Id: req.Id,
        Name:   req.Name,
        Age:    req.Age,
        Class:  req.Class,
        UpdateAt: time.Now().Format("2006-01-02 15:04:05"),
    }

    affected, err := s.Model.Update(student)
    if err != nil {
        return nil, err
    }

    return &types.StudentReply{
        Affected: affected,
    }, nil
}

func (s *StudentService) GetStudent(ctx context.Context, req types.GetStudentRequest) (*types.StudentReply, error) {
    student, err := s.Model.FindOne(req.Id)
    if err != nil {
        return nil, err
    }

    return &types.StudentReply{
        Id: student.Id,
        Name: student.Name,
        Age: student.Age,
        Class: student.Class,
        CreateAt: student.CreateAt,
        UpdateAt: student.UpdateAt,
    }, nil
}

func (s *StudentService) ListStudent(ctx context.Context, req types.ListStudentRequest) (*types.StudentListReply, error) {
    students, err := s.Model.List(req.Offset, req.Limit)
    if err != nil {
        return nil, err
    }

    var studentList []*types.StudentReply
    for _, student := range students {
        studentList = append(studentList, &types.StudentReply{
            Id: student.Id,
            Name: student.Name,
            Age: student.Age,
            Class: student.Class,
            CreateAt: student.CreateAt,
            UpdateAt: student.UpdateAt,
        })
    }

    return &types.StudentListReply{
        List: studentList,
    }, nil
}

In this file, we implement the 5 defined in the student.api file through the service.go file API interface. We defined a StudentService structure, which contains a models.SvcCtx member, through which we can access the database we need.

  1. Front-end code

Next, we build the front-end application through Vue.js. We can use Vue-cli scaffolding to build basic projects. Assume that we have used Vue-cli to create a front-end project named student-mgmt.

In the student-mgmt project, we need to use axios to send HTTP requests to access the back-end API interface. We can make relevant configurations in the main.js file:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

import axios from 'axios'

Vue.prototype.$http = axios
axios.defaults.baseURL = 'http://localhost:8888/student/'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

In the above code, we set axios as the prototype object of Vue, so that this.$http can be used directly in the component to send HTTP requests. We also set the baseURL of axios to the address of the backend API interface, which is http://localhost:8888/student/.

Next, let’s write the component code of student-mgmt. Create the components directory in the student-mgmt directory, and then create a StudentList.vue component in this directory to display the student list:

<template>
  <div>
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Age</th>
          <th>Class</th>
          <th>CreateAt</th>
          <th>UpdateAt</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="student in students" :key="student.id">
          <td>{{ student.id }}</td>
          <td>{{ student.name }}</td>
          <td>{{ student.age }}</td>
          <td>{{ student.class }}</td>
          <td>{{ student.create_at }}</td>
          <td>{{ student.update_at }}</td>
          <td>
            <button @click="deleteStudent(student.id)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>

    <button @click="addStudent()">新增</button>
  </div>
</template>

<script>
export default {
  data () {
    return {
      students: []
    }
  },
  methods: {
    addStudent () {
      this.$router.push('/add')
    },
    deleteStudent (id) {
      this.$http.delete(id).then(() => {
        this.getStudents()
      })
    },
    getStudents () {
      this.$http.get('?limit=20').then(({ data }) => {
        this.students = data.list
      })
    }
  },
  mounted () {
    this.getStudents()
  }
}
</script>

In the above code, we introduced the Vue.js framework and defined A StudentList component. This component is used to display the student list. We use the v-for instruction to traverse the student list data and display it in the table. We also defined an addStudent method to jump to the page where new student information is added. We use axios to send HTTP requests, obtain the student list through the get method, and delete student information through the delete method.

  1. API service registration and startup

After completing the writing of the back-end and front-end code, we also need to register and start the back-end API service. We create a student.go file in the project root directory to define the registration and startup of the service.

We defined the following code in the student.go file:

package main

import (
    "log"

    "zero-study/api/internal/config"
    "zero-study/api/internal/handler"
    "zero-study/api/internal/svc"
    "zero-study/api/internal/types"

    "github.com/tal-tech/go-zero/core/conf"
    "github.com/tal-tech/go-zero/core/logx"
    "github.com/tal-tech/go-zero/core/service"
)

func main() {
    var c config.Config
    conf.MustLoad("config.yaml", &c)

    ctx := svc.NewServiceContext(c)
    srv := service.NewServer(c.ServerConf, handler.NewHandler(ctx))

    types.RegisterStudentApiServer(srv, handler.NewStudentHandler(ctx))

    logx.Must(srv.Start())
}

在该文件中,我们首先通过conf.MustLoad函数来加载config.yaml文件中的配置参数,然后通过svc.NewServiceContext函数来创建服务上下文对象。接着,我们调用service.NewServer函数来创建一个新的服务对象,并将服务配置和Handler传入。最后,我们使用types.RegisterStudentApiServer函数来注册API服务,然后调用srv.Start方法来启动API服务。

完成上述步骤后,我们运行go run student.go命令即可启动API服务。

  1. 总结

在本文中,我们介绍了前后端分离式API服务设计,以及如何使用go-zero和Vue.js来实现该设计模式。通过go-zero和Vue.js的结合,我们可以快速构建出高性能的前后端分离式API服务,提高开发效率和系统维护性。
通过实例的演示,我们可以看出,更多的大型企业在使用前后端分离式API服务设计方案。与fe,iOS,Android甚至小程序方案相比,前后分离式API的开发模式,前端和后端各自专攻、分工明确,API 服务也成了产品经理和各端工程师之间的一个契约。它让不同的客户端直接面向服务器进行对接,除去了 web 页面这种渲染环节,利用了ajax等技术通信。从而加快了前端和后端的开发效率和提高了系统运行的稳定性。

The above is the detailed content of Use go-zero+Vue.js to implement front-end and back-end separated API service design. 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