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

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
Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 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.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Is Golang Faster Than C  ? Exploring the LimitsIs Golang Faster Than C ? Exploring the LimitsApr 20, 2025 am 12:19 AM

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang: From Web Services to System ProgrammingGolang: From Web Services to System ProgrammingApr 20, 2025 am 12:18 AM

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang vs. C  : Benchmarks and Real-World PerformanceGolang vs. C : Benchmarks and Real-World PerformanceApr 20, 2025 am 12:18 AM

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang vs. Python: A Comparative AnalysisGolang vs. Python: A Comparative AnalysisApr 20, 2025 am 12:17 AM

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.