>  기사  >  백엔드 개발  >  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 서비스를 구현하기 위한 백엔드 코드를 작성합니다. 프로젝트의 루트 디렉터리에 학생 디렉터리를 생성한 다음 디렉터리에 학생 정보에 대한 API 인터페이스를 정의하기 위한 Student.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 인터페이스가 정의되어 있습니다. , 학생 정보를 삭제, 수정, 조회 및 나열합니다. 다음으로 학생 디렉토리에 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 인터페이스를 구현합니다. 우리는 필요한 데이터베이스에 액세스할 수 있는 models.SvcCtx 멤버를 포함하는 StudentService 구조를 정의했습니다.

  1. 프런트엔드 코드

다음으로 Vue.js를 통해 프런트엔드 애플리케이션을 빌드합니다. Vue-cli 스캐폴딩을 사용하여 기본 프로젝트를 빌드할 수 있습니다. Vue-cli를 사용하여 Student-mgmt라는 프런트 엔드 프로젝트를 생성했다고 가정합니다.

student-mgmt 프로젝트에서는 백엔드 API 인터페이스에 액세스하기 위해 axios를 사용하여 HTTP 요청을 보내야 합니다. 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 디렉터리에 구성 요소 디렉터리를 생성한 다음 이 디렉터리에 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으로 문의하세요.