go-zero docker-compose 搭建課件服務(二):編寫courseware rpc服務

slowquery發表於2022-08-22

0、轉載

go-zero docker-compose 搭建課件服務(二):編寫courseware rpc服務

0.1原始碼地址

github.com/liuyuede123/go-zero-cou...

1、建立model

mysql中建立資料庫

create database go_zero_courseware default character set utf8mb4 collate utf8mb4_unicode_ci;

建立sql檔案

touch courseware/rpc/model/courseware.sql
CREATE TABLE `courseware`
(
    `id`          bigint unsigned NOT NULL AUTO_INCREMENT,
    `code`        varchar(255) NOT NULL DEFAULT '' COMMENT '編號',
    `name`        varchar(255) NOT NULL DEFAULT '' COMMENT '使用者姓名',
    `type`        tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '課件型別 1-h5 2-scorm 3-多媒體多章節',
    `is_delete`   tinyint(4) NOT NULL DEFAULT 0 COMMENT '是否刪除 0-未刪除 1-已刪除',
    `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
    `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    UNIQUE KEY `idx_mobile_unique` (`mobile`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4;

生成model

# 到對應model目錄下
cd courseware/rpc/model
# 生成model
goctl model mysql ddl -src="./*.sql" -dir="./" -c

2、生成rpc檔案

需要提前安裝了protoc & protoc-gen-go,自行搜尋安裝

# 回到courseware rpc目錄 ./go-zero-courseware/courseware/rpc
cd ../

goctl rpc protoc courseware.proto --go_out=. --go-grpc_out=. --zrpc_out=.

3、初始化module

# 路徑 courseware
go mod init
go mod tidy

4、新增資料庫源

courseware.yaml中增加mysql配置

# 路徑
# go-zero-courseware/courseware/rpc/etc/courseware.yaml

Name: courseware.rpc
ListenOn: 0.0.0.0:9400
Etcd:
  Hosts:
  - etcd:2379
  Key: courseware.rpc


# mysql資料來源
Mysql:
  DataSource: root:liufutian@tcp(192.168.0.110:3306)/go_zero_courseware?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai

# redis快取
CacheRedis:
  - Host: 192.168.0.110:6379
    Pass:

config.go檔案中增加mysql配置項

// 路徑 courseware/rpc/internal/config/config.go
package config

import (
    "github.com/zeromicro/go-zero/core/stores/cache"
    "github.com/zeromicro/go-zero/zrpc"
)

type Config struct {
    zrpc.RpcServerConf

    Mysql struct {
        DataSource string
    }

    CacheRedis cache.CacheConf
}

servicecontext.go中增加CoursewareModel配置

// 路徑 courseware/rpc/internal/svc/servicecontext.go
package svc

import (
    "github.com/zeromicro/go-zero/core/stores/sqlx"
    "go-zero-courseware/courseware/rpc/internal/config"
    "go-zero-courseware/courseware/rpc/model"
)

type ServiceContext struct {
    Config config.Config

    CoursewareModel model.CoursewareModel
}

func NewServiceContext(c config.Config) *ServiceContext {
    conn := sqlx.NewMysql(c.Mysql.DataSource)
    return &ServiceContext{
        Config:          c,
        CoursewareModel: model.NewCoursewareModel(conn, c.CacheRedis),
    }
}

5、編寫增刪改查邏輯

courseware/rpc/internal/logic/addlogic.go修改如下

package logic

import (
    "context"
    "go-zero-courseware/courseware/rpc/courseware"
    "go-zero-courseware/courseware/rpc/internal/svc"
    "go-zero-courseware/courseware/rpc/model"
    "google.golang.org/grpc/status"

    "github.com/zeromicro/go-zero/core/logx"
)

type AddLogic struct {
    ctx    context.Context
    svcCtx *svc.ServiceContext
    logx.Logger
}

func NewAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddLogic {
    return &AddLogic{
        ctx:    ctx,
        svcCtx: svcCtx,
        Logger: logx.WithContext(ctx),
    }
}

func (l *AddLogic) Add(in *courseware.AddRequest) (*courseware.AddResponse, error) {
    _, err := l.svcCtx.CoursewareModel.FindOneByCode(l.ctx, in.Code)
    if err == nil {
        return nil, status.Error(5000, "課件已存在")
    }

    if err == model.ErrNotFound {
        newCourseware := model.Courseware{
            Code: in.Code,
            Name: in.Name,
            Type: in.Type,
        }

        _, err = l.svcCtx.CoursewareModel.Insert(l.ctx, &newCourseware)
        if err != nil {
            return nil, status.Error(500, err.Error())
        }

        return &courseware.AddResponse{}, nil
    }

    return nil, status.Error(500, err.Error())
}

courseware/rpc/internal/logic/deletelogic.go修改如下

package logic

import (
    "context"
    "google.golang.org/grpc/status"

    "go-zero-courseware/courseware/rpc/courseware"
    "go-zero-courseware/courseware/rpc/internal/svc"

    "github.com/zeromicro/go-zero/core/logx"
)

type DeleteLogic struct {
    ctx    context.Context
    svcCtx *svc.ServiceContext
    logx.Logger
}

func NewDeleteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteLogic {
    return &DeleteLogic{
        ctx:    ctx,
        svcCtx: svcCtx,
        Logger: logx.WithContext(ctx),
    }
}

func (l *DeleteLogic) Delete(in *courseware.DeleteRequest) (*courseware.DeleteResponse, error) {
    err := l.svcCtx.CoursewareModel.Delete(l.ctx, in.Id)
    if err != nil {
        return nil, status.Error(500, err.Error())
    }

    return &courseware.DeleteResponse{}, nil
}

courseware/rpc/internal/logic/getlogic.go修改如下

package logic

import (
    "context"
    "google.golang.org/grpc/status"

    "go-zero-courseware/courseware/rpc/courseware"
    "go-zero-courseware/courseware/rpc/internal/svc"

    "github.com/zeromicro/go-zero/core/logx"
)

type GetLogic struct {
    ctx    context.Context
    svcCtx *svc.ServiceContext
    logx.Logger
}

func NewGetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetLogic {
    return &GetLogic{
        ctx:    ctx,
        svcCtx: svcCtx,
        Logger: logx.WithContext(ctx),
    }
}

func (l *GetLogic) Get(in *courseware.GetRequest) (*courseware.GetResponse, error) {
    cw, err := l.svcCtx.CoursewareModel.FindOne(l.ctx, in.Id)
    if err != nil {
        return nil, status.Error(5000, "課件不存在")
    }

    return &courseware.GetResponse{
        Id:   cw.Id,
        Code: cw.Code,
        Name: cw.Name,
        Type: cw.Type,
    }, nil
}

courseware/rpc/internal/logic/updatelogic.go修改如下:

package logic

import (
    "context"
    "google.golang.org/grpc/status"

    "go-zero-courseware/courseware/rpc/courseware"
    "go-zero-courseware/courseware/rpc/internal/svc"

    "github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
    ctx    context.Context
    svcCtx *svc.ServiceContext
    logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
    return &UpdateLogic{
        ctx:    ctx,
        svcCtx: svcCtx,
        Logger: logx.WithContext(ctx),
    }
}

func (l *UpdateLogic) Update(in *courseware.UpdateRequest) (*courseware.UpdateResponse, error) {
    cw, err := l.svcCtx.CoursewareModel.FindOne(l.ctx, in.Id)
    if err != nil {
        return nil, status.Error(5000, "課件不存在")
    }

    _, err = l.svcCtx.CoursewareModel.FindOneByCode(l.ctx, in.Code)
    if err == nil {
        return nil, status.Error(5000, "課件編號已存在")
    }

    if in.Code != "" {
        cw.Code = in.Code
    }
    if in.Name != "" {
        cw.Name = in.Name
    }
    if in.Type > 0 {
        cw.Type = in.Type
    }
    err = l.svcCtx.CoursewareModel.Update(l.ctx, cw)
    if err != nil {
        return nil, status.Error(500, err.Error())
    }

    return &courseware.UpdateResponse{}, nil
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章