ホームページ  >  記事  >  バックエンド開発  >  go-zero+Vue.js を使用してフロントエンドとバックエンドに分離された API サービス設計を実装する

go-zero+Vue.js を使用してフロントエンドとバックエンドに分離された API サービス設計を実装する

WBOY
WBOYオリジナル
2023-06-23 08:46:291160ブラウズ

今日の急速に発展するインターネット時代では、フロントエンドとバックエンドの分離された API サービス設計が非常に一般的な設計アイデアになっています。この設計思想を利用すると、フロントエンドコードとバックエンドコードを別々に開発できるため、開発の効率化とシステムの保守性の向上が実現できます。この記事では、go-zero と Vue.js を使用して、フロントエンドとバックエンドに分離された API サービス設計を実装する方法を紹介します。

1. フロントエンドとバックエンドの分離された API サービス設計の利点

フロントエンドとフロントエンドの分離された API サービス設計の利点には、主に次の側面が含まれます:

  1. 開発効率の向上

フロントエンドとバックエンドを分離したAPIサービス設計を採用することで、フロントエンドとバックエンドの開発を手間をかけずに並行して行うことができます。開発作業の次のステップに進む前に、相手方の開発が完了するのを待たなければなりません。これにより、開発サイクルを短縮し、開発効率を向上させることができます。

  1. クロスプラットフォームの実現

フロントエンドとバックエンドの分離された API サービス設計を使用して、フロントエンドとバックエンドを異なるサーバーにデプロイできます。それぞれクロスプラットフォームを実現します。これにより、さまざまなニーズやシナリオにうまく適応できます。

  1. システムの保守性の向上

フロントエンドとバックエンドを分離した API サービス設計を使用すると、フロントエンドとバックエンドのコードを分離できるため、メンテナンスが容易になります。フロントエンド開発者とバックエンド開発者は、それぞれ独自のコード保守を担当できるため、ソフトウェア保守の困難さとリスクを軽減できます。

2. go-zero の概要

go-zero は、高性能マイクロサービス アプリケーションを迅速に構築するための豊富な機能とプラグインを提供する高性能マイクロサービス開発フレームワークです。 go-zero は、HTTP、gRPC、TCP などの複数のトランスポート プロトコルをサポートします。 ETCD、Redis、MySQL などのさまざまなミドルウェアも提供しており、サービス登録、構成センター、ストレージなどの機能を簡単に実装できます。

3. Vue.js の概要

Vue.js は、非常に人気のあるフロントエンド JavaScript フレームワークであり、MVVM (Model-View-ViewModel) アーキテクチャ パターンを採用しており、豊富な機能を提供します。コンポーネントとプラグインを使用すると、効率的なフロントエンド アプリケーションを迅速に構築できます。 Vue.js はデータ駆動型開発モデルに従っており、DOM 操作の数を減らし、フロントエンド アプリケーションのパフォーマンスを向上させることができます。

4. 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
}

このファイルでは、student.api ファイルで定義されている 5 を、service.go ファイルを通じて実装します。 APIインターフェース。ここでは、models.SvcCtx メンバーを含む StudentService 構造体を定義しました。この構造体を通じて、必要なデータベースにアクセスできます。

  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 のベース URL をバックエンド API インターフェイスのアドレス (http://localhost:8888/student/) に設定します。

次に、student-mgmtのコンポーネントコードを書いていきます。 Student-mgmt ディレクトリにコンポーネント ディレクトリを作成し、このディレクトリに 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 フレームワークを導入し、A を定義しました。 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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。