• Enter the service workspace
$ cd mall/service/product
Copy the code

5.1 Generation of Product Model

  • Create SQL file
$ vim model/product.sql
Copy the code
  • Writing SQL files
CREATE TABLE `product` (
	`id` bigint unsigned NOT NULL AUTO_INCREMENT,
	`name` varchar(255)  NOT NULL DEFAULT ' ' COMMENT 'Product Name',
	`desc` varchar(255)  NOT NULL DEFAULT ' ' COMMENT 'Product Description',
        `stock` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'Product Inventory',
	`amount` int(10) unsigned NOT NULL DEFAULT '0'  COMMENT 'Product Amount',
	`status` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT 'Product Status',
	`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
	`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP.PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4;
Copy the code
  • Run the template generation command
$ goctl model mysql ddl -src ./model/product.sql -dir ./model -c
Copy the code

5.2 Generating the Product API Service

  • Creating an API file
$ vim api/product.api
Copy the code
  • Writing API files
type (
	// Product creation
	CreateRequest {
		Name   string `json:"name"`
		Desc   string `json:"desc"`
		Stock  int64  `json:"stock"`
		Amount int64  `json:"amount"`
		Status int64  `json:"status"`
	}
	CreateResponse {
		Id int64 `json:"id"`
	}
	// Product creation

	// Product modification
	UpdateRequest {
		Id     int64  `json:"id"`
		Name   string `json:"name,optional"`
		Desc   string `json:"desc,optional"`
		Stock  int64  `json:"stock"`
		Amount int64  `json:"amount,optional"`
		Status int64  `json:"status,optional"`
	}
	UpdateResponse {
	}
	// Product modification

	// Delete the product
	RemoveRequest {
		Id int64 `json:"id"`
	}
	RemoveResponse {
	}
	// Delete the product

	// Product details
	DetailRequest {
		Id int64 `json:"id"`
	}
	DetailResponse {
		Id     int64  `json:"id"`
		Name   string `json:"name"`
		Desc   string `json:"desc"`
		Stock  int64  `json:"stock"`
		Amount int64  `json:"amount"`
		Status int64  `json:"status"`
	}
	// Product details
)

@server(
	jwt: Auth
)
service Product {
	@handler Create
	post /api/product/create(CreateRequest) returns (CreateResponse)
	
	@handler Update
	post /api/product/update(UpdateRequest) returns (UpdateResponse)
	
	@handler Remove
	post /api/product/remove(RemoveRequest) returns (RemoveResponse)
	
	@handler Detail
	post /api/product/detail(DetailRequest) returns (DetailResponse)
}
Copy the code
  • Run the template generation command
$ goctl api go -api ./api/product.api -dir ./api
Copy the code

5.3 Generating the Product RPC Service

  • Create the proto file
$ vim rpc/product.proto
Copy the code
  • Write proto files
syntax = "proto3";

package productclient;

option go_package = "product";

// Product creation
message CreateRequest {
    string Name = 1;
    string Desc = 2;
    int64 Stock = 3;
    int64 Amount = 4;
    int64 Status = 5;
}
message CreateResponse {
	int64 id = 1;
}
// Product creation

// Product modification
message UpdateRequest {
    int64 id = 1;
    string Name = 2;
    string Desc = 3;
    int64 Stock = 4;
    int64 Amount = 5;
    int64 Status = 6;
}
message UpdateResponse {}// Product modification

// Delete the product
message RemoveRequest {
    int64 id = 1;
}
message RemoveResponse {}// Delete the product

// Product details
message DetailRequest {
    int64 id = 1;
}
message DetailResponse {
    int64 id = 1;
    string Name = 2;
    string Desc = 3;
    int64 Stock = 4;
    int64 Amount = 5;
    int64 Status = 6;
}
// Product details

service Product {
    rpc Create(CreateRequest) returns(CreateResponse);
    rpc Update(UpdateRequest) returns(UpdateResponse);
    rpc Remove(RemoveRequest) returns(RemoveResponse);
    rpc Detail(DetailRequest) returns(DetailResponse);
}
Copy the code
  • Run the template generation command
$ goctl rpc proto -src ./rpc/product.proto -dir ./rpc
Copy the code

5.4 Writing the Product RPC Service

5.4.1 Modifying a Configuration File

  • Modify the product.yaml configuration file
$ vim rpc/etc/product.yaml
Copy the code
  • Change the service listening address to 0.0.0.0:9001.EtcdService configuration,MysqlService configuration,CacheRedisService configuration
Name: product.rpc
ListenOn: 0.0. 0. 0: 9001

Etcd:
  Hosts:
  - etcd:2379
  Key: product.rpc

Mysql:
  DataSource: root:123456@tcp(mysql:3306)/mall? charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai

CacheRedis:
- Host: redis:6379
  Type: node
  Pass:
Copy the code

5.4.2 Adding a Product Model dependency

  • addMysqlService configuration,CacheRedisInstantiation of the service configuration
$ vim rpc/internal/config/config.go
Copy the code
package config

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

type Config struct {
	zrpc.RpcServerConf

	Mysql struct {
		DataSource string
	}
  
	CacheRedis cache.CacheConf
}
Copy the code
  • Register the service Contextproduct modelThe dependence of
$ vim rpc/internal/svc/servicecontext.go
Copy the code
package svc

import (
	"mall/service/product/model"
	"mall/service/product/rpc/internal/config"

	"github.com/tal-tech/go-zero/core/stores/sqlx"
)

type ServiceContext struct {
	Config config.Config
    
	ProductModel model.ProductModel
}

func NewServiceContext(c config.Config) *ServiceContext {
	conn := sqlx.NewMysql(c.Mysql.DataSource)
	return &ServiceContext{
		Config:       c,
		ProductModel: model.NewProductModel(conn, c.CacheRedis),
	}
}
Copy the code

5.4.3 Adding a Product Create logic Create

$ vim rpc/internal/logic/createlogic.go
Copy the code
package logic

import (
	"context"

	"mall/service/product/model"
	"mall/service/product/rpc/internal/svc"
	"mall/service/product/rpc/product"

	"github.com/tal-tech/go-zero/core/logx"
	"google.golang.org/grpc/status"
)

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

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

func (l *CreateLogic) Create(in *product.CreateRequest) (*product.CreateResponse, error) {
	newProduct := model.Product{
		Name:   in.Name,
		Desc:   in.Desc,
		Stock:  in.Stock,
		Amount: in.Amount,
		Status: in.Status,
	}

	res, err := l.svcCtx.ProductModel.Insert(&newProduct)
	iferr ! =nil {
		return nil, status.Error(500, err.Error())
	}

	newProduct.Id, err = res.LastInsertId()
	iferr ! =nil {
		return nil, status.Error(500, err.Error())
	}

	return &product.CreateResponse{
		Id: newProduct.Id,
	}, nil
}
Copy the code

5.4.4 Adding logical details

$ vim rpc/internal/logic/detaillogic.go
Copy the code
package logic

import (
	"context"

	"mall/service/product/model"
	"mall/service/product/rpc/internal/svc"
	"mall/service/product/rpc/product"

	"github.com/tal-tech/go-zero/core/logx"
	"google.golang.org/grpc/status"
)

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

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

func (l *DetailLogic) Detail(in *product.DetailRequest) (*product.DetailResponse, error) {
	// Check whether the product exists
	res, err := l.svcCtx.ProductModel.FindOne(in.Id)
	iferr ! =nil {
		if err == model.ErrNotFound {
			return nil, status.Error(100."The product does not exist")}return nil, status.Error(500, err.Error())
	}

	return &product.DetailResponse{
		Id:     res.Id,
		Name:   res.Name,
		Desc:   res.Desc,
		Stock:  res.Stock,
		Amount: res.Amount,
		Status: res.Status,
	}, nil
}
Copy the code

5.4.5 Adding the Product Update Logic Update

$ vim rpc/internal/logic/updatelogic.go
Copy the code
package logic

import (
	"context"

	"mall/service/product/model"
	"mall/service/product/rpc/internal/svc"
	"mall/service/product/rpc/product"

	"github.com/tal-tech/go-zero/core/logx"
	"google.golang.org/grpc/status"
)

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 *product.UpdateRequest) (*product.UpdateResponse, error) {
	// Check whether the product exists
	res, err := l.svcCtx.ProductModel.FindOne(in.Id)
	iferr ! =nil {
		if err == model.ErrNotFound {
			return nil, status.Error(100."The product does not exist")}return nil, status.Error(500, err.Error())
	}

	ifin.Name ! ="" {
		res.Name = in.Name
	}
	ifin.Desc ! ="" {
		res.Desc = in.Desc
	}
	ifin.Stock ! =0 {
		res.Stock = in.Stock
	}
	ifin.Amount ! =0 {
		res.Amount = in.Amount
	}
	ifin.Status ! =0 {
		res.Status = in.Status
	}

	err = l.svcCtx.ProductModel.Update(res)
	iferr ! =nil {
		return nil, status.Error(500, err.Error())
	}

	return &product.UpdateResponse{}, nil
}
Copy the code

5.4.6 Adding a Product Delete logical Remove

$ vim rpc/internal/logic/removelogic.go
Copy the code
package logic

import (
	"context"

	"mall/service/product/model"
	"mall/service/product/rpc/internal/svc"
	"mall/service/product/rpc/product"

	"github.com/tal-tech/go-zero/core/logx"
	"google.golang.org/grpc/status"
)

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

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

func (l *RemoveLogic) Remove(in *product.RemoveRequest) (*product.RemoveResponse, error) {
	// Check whether the product exists
	res, err := l.svcCtx.ProductModel.FindOne(in.Id)
	iferr ! =nil {
		if err == model.ErrNotFound {
			return nil, status.Error(100."The product does not exist")}return nil, status.Error(500, err.Error())
	}

	err = l.svcCtx.ProductModel.Delete(res.Id)
	iferr ! =nil {
		return nil, status.Error(500, err.Error())
	}

	return &product.RemoveResponse{}, nil
}
Copy the code

5.5 Writing the Product API Service

5.5.1 Modifying the Configuration File

  • Modify the product.yaml configuration file
$ vim api/etc/product.yaml
Copy the code
  • Change the service address to 0.0.0.0:8001.MysqlService configuration,CacheRedisService configuration,AuthVerify the configuration
Name: Product
Host: 0.0. 0. 0
Port: 8001

Mysql:
  DataSource: root:123456@tcp(mysql:3306)/mall? charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai

CacheRedis:
- Host: redis:6379
  Type: node
  Pass:

Auth:
  AccessSecret: uOvKLmVfztaXGpNYd4Z0I1SiT7MweJhl
  AccessExpire: 86400
Copy the code

5.5.2 Adding a Product RPC Dependency

  • addproduct rpcService configuration
$ vim api/etc/product.yaml
Copy the code
Name: Product
Host: 0.0. 0. 0
Port: 8001

.

ProductRpc:
  Etcd:
    Hosts:
    - etcd:2379
    Key: product.rpc
Copy the code
  • addproduct rpcInstantiation of the service configuration
$ vim api/internal/config/config.go
Copy the code
package config

import (
	"github.com/tal-tech/go-zero/rest"
	"github.com/tal-tech/go-zero/zrpc"
)

type Config struct {
	rest.RestConf

	Auth struct {
		AccessSecret string
		AccessExpire int64
	}

	ProductRpc zrpc.RpcClientConf
}
Copy the code
  • Register the service Contextproduct rpcThe dependence of
$ vim api/internal/svc/servicecontext.go
Copy the code
package svc

import (
	"mall/service/product/api/internal/config"
	"mall/service/product/rpc/productclient"

	"github.com/tal-tech/go-zero/zrpc"
)

type ServiceContext struct {
	Config config.Config
    
	ProductRpc productclient.Product
}

func NewServiceContext(c config.Config) *ServiceContext {
	return &ServiceContext{
		Config:     c,
		ProductRpc: productclient.NewProduct(zrpc.MustNewClient(c.ProductRpc)),
	}
}
Copy the code

5.5.3 Adding a Product Create logic Create

$ vim api/internal/logic/createlogic.go
Copy the code
package logic

import (
	"context"

	"mall/service/product/api/internal/svc"
	"mall/service/product/api/internal/types"
	"mall/service/product/rpc/product"

	"github.com/tal-tech/go-zero/core/logx"
)

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

func NewCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) CreateLogic {
	return CreateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateLogic) Create(req types.CreateRequest) (resp *types.CreateResponse, err error) {
	res, err := l.svcCtx.ProductRpc.Create(l.ctx, &product.CreateRequest{
		Name:   req.Name,
		Desc:   req.Desc,
		Stock:  req.Stock,
		Amount: req.Amount,
		Status: req.Status,
	})
	iferr ! =nil {
		return nil, err
	}

	return &types.CreateResponse{
		Id: res.Id,
	}, nil
}
Copy the code

5.5.4 Adding logical Detail of product details

$ vim api/internal/logic/detaillogic.go
Copy the code
package logic

import (
	"context"

	"mall/service/product/api/internal/svc"
	"mall/service/product/api/internal/types"
	"mall/service/product/rpc/product"

	"github.com/tal-tech/go-zero/core/logx"
)

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

func NewDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) DetailLogic {
	return DetailLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DetailLogic) Detail(req types.DetailRequest) (resp *types.DetailResponse, err error) {
	res, err := l.svcCtx.ProductRpc.Detail(l.ctx, &product.DetailRequest{
		Id: req.Id,
	})
	iferr ! =nil {
		return nil, err
	}

	return &types.DetailResponse{
		Id:     res.Id,
		Name:   res.Name,
		Desc:   res.Desc,
		Stock:  res.Stock,
		Amount: res.Amount,
		Status: res.Status,
	}, nil
}
Copy the code

5.5.5 Adding the Product Update Logic Update

$ vim api/internal/logic/updatelogic.go
Copy the code
package logic

import (
	"context"

	"mall/service/product/api/internal/svc"
	"mall/service/product/api/internal/types"
	"mall/service/product/rpc/product"

	"github.com/tal-tech/go-zero/core/logx"
)

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

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

func (l *UpdateLogic) Update(req types.UpdateRequest) (resp *types.UpdateResponse, err error) {
	_, err = l.svcCtx.ProductRpc.Update(l.ctx, &product.UpdateRequest{
		Id:     req.Id,
		Name:   req.Name,
		Desc:   req.Desc,
		Stock:  req.Stock,
		Amount: req.Amount,
		Status: req.Status,
	})

	iferr ! =nil {
		return nil, err
	}

	return &types.UpdateResponse{}, nil
}
Copy the code

5.5.6 Adding a Product Delete logical Remove

$ vim api/internal/logic/removelogic.go
Copy the code
package logic

import (
	"context"

	"mall/service/product/api/internal/svc"
	"mall/service/product/api/internal/types"
	"mall/service/product/rpc/product"

	"github.com/tal-tech/go-zero/core/logx"
)

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

func NewRemoveLogic(ctx context.Context, svcCtx *svc.ServiceContext) RemoveLogic {
	return RemoveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RemoveLogic) Remove(req types.RemoveRequest) (resp *types.RemoveResponse, err error) {
	_, err = l.svcCtx.ProductRpc.Remove(l.ctx, &product.RemoveRequest{
		Id: req.Id,
	})
	iferr ! =nil {
		return nil, err
	}

	return &types.RemoveResponse{}, nil
}
Copy the code

5.6 Starting the Product RPC Service

! Tip: To start the service, you need to start it in the Golang container

$ cdMall /service/product/ RPC $go run product. Go -f etc/product. Yaml Starting RPC server at 127.0.0.1:9001...Copy the code

5.7 Starting the Product API Service

! Tip: To start the service, you need to start it in the Golang container

$ cdMall /service/product/ API $go run product. Go -f etc/product. Yaml Starting server at 0.0.0.0:8001...Copy the code

Project address: Github

Previous article “Go-Zero: Let micro Services Go — 4 User Services”

The next post is “Go-Zero: Making Microservices Go — order”.