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

在當今快速發展的網路時代,前後端分離式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
初始功能和副作用:平衡初始化與可維護性初始功能和副作用:平衡初始化與可維護性Apr 26, 2025 am 12:23 AM

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

開始GO:初學者指南開始GO:初學者指南Apr 26, 2025 am 12:21 AM

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

進行並發模式:開發人員的最佳實踐進行並發模式:開發人員的最佳實踐Apr 26, 2025 am 12:20 AM

開發者應遵循以下最佳實踐:1.謹慎管理goroutines以防止資源洩漏;2.使用通道進行同步,但避免過度使用;3.在並發程序中顯式處理錯誤;4.了解GOMAXPROCS以優化性能。這些實踐對於高效和穩健的軟件開發至關重要,因為它們確保了資源的有效管理、同步的正確實現、錯誤的適當處理以及性能的優化,從而提升軟件的效率和可維護性。

進行生產:現實世界的用例和示例進行生產:現實世界的用例和示例Apr 26, 2025 am 12:18 AM

Goexcelsinproductionduetoitsperformanceandsimplicity,butrequirescarefulmanagementofscalability,errorhandling,andresources.1)DockerusesGoforefficientcontainermanagementthroughgoroutines.2)UberscalesmicroserviceswithGo,facingchallengesinservicemanageme

go中的自定義錯誤類型:提供詳細的錯誤信息go中的自定義錯誤類型:提供詳細的錯誤信息Apr 26, 2025 am 12:09 AM

我們需要自定義錯誤類型,因為標準錯誤接口提供的信息有限,自定義類型能添加更多上下文和結構化信息。 1)自定義錯誤類型能包含錯誤代碼、位置、上下文數據等,2)提高調試效率和用戶體驗,3)但需注意其複雜性和維護成本。

使用GO編程語言構建可擴展系統使用GO編程語言構建可擴展系統Apr 25, 2025 am 12:19 AM

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建築物內currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

有效地使用Init功能的最佳實踐有效地使用Init功能的最佳實踐Apr 25, 2025 am 12:18 AM

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用輔助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

INIT函數在GO軟件包中的執行順序INIT函數在GO軟件包中的執行順序Apr 25, 2025 am 12:14 AM

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中