首頁  >  文章  >  後端開發  >  利用go-zero+Vue.js實現前後端分離式API服務設計

利用go-zero+Vue.js實現前後端分離式API服務設計

WBOY
WBOY原創
2023-06-23 08:46:291159瀏覽

在當今快速發展的網路時代,前後端分離式API服務設計已經成為一種非常流行的設計想法。使用這種設計思想,我們可以將前端程式碼和後端程式碼分開開發,從而實現更有效率的開發和更良好的系統維護性。本文將介紹如何透過使用go-zero和Vue.js來實現前後端分離式API服務設計。

一、前後端分離式API服務設計的優點

前後端分離式API服務設計的優勢主要有以下幾個面向:

  1. 開發效率更高

使用前後端分離式API服務設計可以將前端和後端的開發並行進行,不必等待對方開發完成才能進行下一步開發工作。這樣可以縮短開發週期,提高開發效率。

  1. 實作跨平台

使用前後端分離式API服務設計,前後端可以分別部署在不同的伺服器上,實現跨平台。這樣可以更適應不同的需求和場景。

  1. 提高系統維護性

使用前後端分離式API服務設計可以將前端和後端程式碼分開,使得維護更加容易。前端和後端開發人員可以分別負責各自的程式碼維護,這樣可以降低軟體維護的難度和風險。

二、go-zero介紹

go-zero是一款高效能的微服務開發框架,提供了豐富的功能和插件,可以快速建立高效能的微服務應用。 go-zero支援多種傳輸協議,包括HTTP、gRPC和TCP等。它還提供了多種中間件,包括ETCD、Redis、MySQL等,可以輕鬆實現服務註冊、配置中心和儲存等功能。

三、Vue.js介紹

Vue.js是一款非常流行的前端JavaScript框架,它採用了MVVM(Model-View-ViewModel)的架構模式,提供了豐富的組件和插件,可以快速建構出高效率的前端應用。 Vue.js遵循資料驅動的開發模式,可以減少DOM操作的次數,提升前端應用的效能。

四、利用go-zero和Vue.js實作前後端分離式API服務設計

首先,我們需要使用go-zero建置後端服務。 go-zero提供了豐富的插件和中介軟體,我們可以快速建立高效能的API服務。接著,我們使用Vue.js建構前端應用,透過HTTP協定呼叫後端API服務,實現前後端分離式的API服務設計。

下面我們以一個簡單的學生資訊管理系統為例,來示範如何使用go-zero和Vue.js實作前後端分離式API服務設計。

  1. 後端程式碼

我們先來寫後端程式碼,透過go-zero框架來實作API服務。在專案的根目錄下建立一個student目錄,然後在該目錄下建立一個student.api文件,定義學生資訊的API介面:

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)
}

我們在該文件中定義了5個API接口,分別用於增加、刪除、修改、查詢和清單學生資訊。接著,我們在student目錄下建立一個service.go文件,實現學生資訊的服務介面:

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
}

在該文件中,我們透過service.go文件實現了student.api文件中定義的5個API介面。我們定義了一個StudentService結構體,該結構體包含一個models.SvcCtx成員,透過該成員來存取我們需要的資料庫。

  1. 前端程式碼

接下來,我們透過Vue.js來建立前端應用程式。我們可以使用Vue-cli腳手架來搭建基礎的工程。假設我們已經使用Vue-cli建立好了名為student-mgmt的前端工程。

在student-mgmt工程中,我們需要使用axios來傳送HTTP請求來存取後端API介面。我們可以在main.js檔案中進行相關設定:

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')

在上述程式碼中,我們將axios設定為Vue的原型對象,以便在元件中可以直接使用this.$http來傳送HTTP請求。我們也將axios的baseURL設定為後端API介面的位址,也就是http://localhost:8888/student/。

接著,我們來寫student-mgmt的元件程式碼。在student-mgmt目錄下建立components目錄,然後在該目錄下建立一個StudentList.vue元件,用於展示學生清單:

<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>

在上述程式碼中,我們引入了Vue.js框架,並定義了一個StudentList元件。該元件用於展示學生列表,我們使用了v-for指令來遍歷學生列表數據,並展示在表格中。我們也定義了一個addStudent方法,用於跳到新增學生資訊的頁面。我們使用axios來發送HTTP請求,透過get方法來取得學生列表,透過delete方法來刪除學生資訊。

  1. API服務註冊和啟動

在完成了後端和前端程式碼的撰寫後,我們還需要將後端API服務註冊並啟動。我們在專案根目錄下建立一個student.go文件,用於定義服務的註冊和啟動。

我們在student.go檔案中定義如下程式碼:

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等技术通信。从而加快了前端和后端的开发效率和提高了系统运行的稳定性。

以上是利用go-zero+Vue.js實現前後端分離式API服務設計的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn