[golang gin framework] 43. Gin mall project - addition, deletion, modification and query of administrators of Rbac microservices in the background after microservices actual combat, and administrator and role association

The previous section explained the addition, deletion, modification, and query of the background Rbac microservice role . Here, we explain the addition, deletion, modification, and query of the authority management Rbac microservice administrator and the microservice function associated with the administrator and the role.

 1. Realize background authority management Rbac administrators add, delete, modify and check microservice server functions

1. Create a Manager model 

To realize the addition, deletion, modification and query of the administrator, it is necessary to create a corresponding model, so create a manager.go model file under server/rbac/models, refer to [ golang gin framework] 14. Gin mall project-RBAC management code is as follows: 

package models

//管理员表

type Manager struct { // 结构体首字母大写, 和数据库表名对应, 默认访问数据表users, 可以设置访问数据表的方法
	Id  int
	Username string
	Password string
	Mobile string
	Email string
	Status int
	RoleId int
	AddTime int
	IsSuper int
	Role Role `gorm:"foreignKey:RoleId;references:Id"`  // 配置关联关系
}

//配置数据库操作的表名称
func (Manager) TableName() string {
	return "manager"
}

 2. Create rbacManager.proto under the proto folder

 Refer to [golang gin framework] 14. Gin mall project - RBAC management , create rbacManager.proto. Generate administrator related methods, the specific code is as follows:

syntax = "proto3";

package manager;

option go_package = "./proto/rbacManager";

//管理员管理微服务rpc方法
service RbacManager {
	//获取管理员rpc方法: 请求参数ManagerGetRequest, 响应参数ManagerGetResponse
    rpc ManagerGet(ManagerGetRequest) returns (ManagerGetResponse) {}
    //增加管理员rpc方法: 请求参数ManagerAddRequest, 响应参数ManagerAddResponse
    rpc ManagerAdd(ManagerAddRequest) returns (ManagerAddResponse) {}
    //编辑管理员rpc方法: 请求参数ManagerEditRequest, 响应参数ManagerEditResponse
    rpc ManagerEdit(ManagerEditRequest) returns (ManagerEditResponse) {}
    //删除管理员rpc方法: 请求参数ManagerDeleteRequest, 响应参数ManagerDeleteResponse
    rpc ManagerDelete(ManagerDeleteRequest) returns (ManagerDeleteResponse) {}
}

//管理员对应的结构体
message ManagerModel{
	int64 id=1;
	string username=2;
	string password=3;
	string mobile=4;
	string email=5;
	int64 status =6;
	int64 roleId=7;
	int64 addTime=8;
	int64 isSuper=9;
	RoleModel role=10;  // 管理员关联的角色
}

//角色对应的结构体
message RoleModel{
	int64 id=1;
	string title=2;
	string description=3;
	int64 status=4;
	int64 addTime =5;
}

//获取管理员请求参数, 当传入id或者管理员名称时,获取对应的管理员数据,如果什么都没传入,则获取管理员列表
message ManagerGetRequest{
	int64 id =1;
	string username =2;
}

//获取管理员响应参数
message ManagerGetResponse{
	repeated ManagerModel ManagerList=1;  //返回管理员切片
}

//增加管理员请求参数
message ManagerAddRequest{
	string username=1;
	string password=2;
	string mobile=3;
	string email=4;
	int64 status =5;
	int64 roleId=6;
	int64 addTime=7;
	int64 isSuper=8;
}

//增加管理员响应参数
message ManagerAddResponse{
	bool success=1;
	string message=2;
}

//编辑管理员请求参数
message ManagerEditRequest{
	int64 id=1;
	string username=2;
	string password=3;
	string mobile=4;
	string email=5;
	int64 status =6;
	int64 roleId=7;
	int64 addTime=8;
	int64 isSuper=9;
}

//编辑管理员响应参数
message ManagerEditResponse{
	bool success=1;
	string message=2;
}

//删除管理员请求参数
message ManagerDeleteRequest{
	int64 id=1;
}

//删除管理员响应参数
message ManagerDeleteResponse{
	bool success=1;
	string message=2;
}

3. Generate manager related pb.go, pb.micro.go files

Run the command protoc --proto_path=. --micro_out=. --go_out=:.proto/rbacManager.proto under server/rbac

 4. Create the rbacManager.go file under the handler folder to implement the service method in proto

Refer to [golang gin framework] 14. Gin mall project - RBAC management_ role addition, deletion, modification and query method code, the specific rbacManager.go code is as follows:

package handler

import (
	"context"
	"strconv"
	"rbac/models"
	pb "rbac/proto/rbacManager"
)

type RbacManager struct{}

//获取管理员
func (e *RbacManager) ManagerGet(ctx context.Context, req *pb.ManagerGetRequest, res *pb.ManagerGetResponse) error {
	managerList := []models.Manager{}
	where := "1=1"
	if req.Id > 0 { // 当传入管理员id时,获取对应的管理员数据, 当没有传入管理员id时,获取管理员列表数据
		where += " AND id=" + strconv.Itoa(int(req.Id))
	}
	if len(req.Username) > 0 { //判断是否传入管理员名称
		where += " AND username=" + req.Username
	}
	models.DB.Where(where).Preload("Role").Find(&managerList)  //获取管理员数据自己对应的关联角色数据
	//处理数据
	var tempList []*pb.ManagerModel
	for _, v := range managerList {
		tempList = append(tempList, &pb.ManagerModel{
			Id:       int64(v.Id),
			Username: v.Username,
			Mobile:   v.Mobile,
			Email:    v.Email,
			Status:   int64(v.Status),
			RoleId:   int64(v.RoleId),
			AddTime:  int64(v.AddTime),
			IsSuper:  int64(v.IsSuper),
			Role: &pb.RoleModel{  //角色数据,可根据自己项目情况获取自己想要的数据
				Title:       v.Role.Title,
				Description: v.Role.Description,
			},
		})
	}

	res.ManagerList = tempList
	return nil
}

//增加管理员
func (e *RbacManager) ManagerAdd(ctx context.Context, req *pb.ManagerAddRequest, res *pb.ManagerAddResponse) error {
	//执行增加管理员
	manager := models.Manager{
		Username: req.Username,
		Password: req.Password,
		Email:    req.Email,
		Mobile:   req.Mobile,
		RoleId:   int(req.RoleId),
		Status:   int(req.Status),
		AddTime:  int(req.AddTime),
	}
	err := models.DB.Create(&manager).Error
	if err != nil {
		res.Success = false
		res.Message = "增加数据失败"
	} else {
		res.Success = true
		res.Message = "增加数据成功"
	}
	return err
}

//修改管理员
func (e *RbacManager) ManagerEdit(ctx context.Context, req *pb.ManagerEditRequest, res *pb.ManagerEditResponse) error {
	//执行修改
	manager := models.Manager{Id: int(req.Id)}
	models.DB.Find(&manager)
	manager.Username = req.Username
	manager.Email = req.Email
	manager.Mobile = req.Mobile
	manager.RoleId = int(req.RoleId)

	//注意:判断密码是否为空 为空表示不修改密码 不为空表示修改密码
	if req.Password != "" {
		manager.Password = req.Password
	}
	err := models.DB.Save(&manager).Error
	if err != nil {
		res.Success = false
		res.Message = "修改数据失败"
	} else {
		res.Success = true
		res.Message = "修改数据成功"
	}
	return err
}

//删除管理员
func (e *RbacManager) ManagerDelete(ctx context.Context, req *pb.ManagerDeleteRequest, res *pb.ManagerDeleteResponse) error {
	manager := models.Manager{Id: int(req.Id)}
    //这里可以是物理删除或者逻辑删除,根据自己项目情况选择
	err := models.DB.Delete(&manager).Error
	if err != nil {
		res.Success = false
		res.Message = "删除数据失败"
	} else {
		res.Success = true
		res.Message = "删除数据成功"
	}

	return err
}

5. Register the administrator microservice in the main.go file

Just import pbManager "rbac/proto/rbacManager" and add the following code in main(): 

// Register handler:注册管理员微服务
	if err := pbRole.RegisterRbacManagerHandler(srv.Server(), new(handler.RbacManager)); err != nil {
		logger.Fatal(err)
	}

The specific code is as follows:

package main

import (
	"rbac/handler"
	"rbac/models"
	pb "rbac/proto/rbacLogin"
	pbRole "rbac/proto/rbacRole"
	pbManager "rbac/proto/rbacManager"
	"go-micro.dev/v4"
	"go-micro.dev/v4/logger"
	"github.com/go-micro/plugins/v4/registry/consul"
)

var (
	service = "rbac"
	version = "latest"
)

func main() {
	//集成consul
	consulReg := consul.NewRegistry()
	// Create service

	//读取.ini里面的配置
	addr := models.Config.Section("consul").Key("addr").String()

	srv := micro.NewService(
		micro.Address(addr),  //指定微服务的ip:  选择注册服务器地址,也可以不配置,默认为本机,也可以选择consul集群中的client
		micro.Name(service),
		micro.Version(version),
		//注册consul
		micro.Registry(consulReg),
	)
	srv.Init(
		micro.Name(service),
		micro.Version(version),
	)

	// Register handler:注册登录微服务
	if err := pb.RegisterRbacLoginHandler(srv.Server(), new(handler.RbacLogin)); err != nil {
		logger.Fatal(err)
	}

	// Register handler:注册角色微服务
	if err := pbRole.RegisterRbacRoleHandler(srv.Server(), new(handler.RbacRole)); err != nil {
		logger.Fatal(err)
	}

	// Register handler:注册管理员微服务
	if err := pbManager.RegisterRbacManagerHandler(srv.Server(), new(handler.RbacManager)); err != nil {
		logger.Fatal(err)
	}
	// Run service
	if err := srv.Run(); err != nil {
		logger.Fatal(err)
	}
}

2. Realize the background authority management Rbac administrator client micro-service function

Refer to [golang gin framework] 41.Gin mall project-background Rbac microservice after microservice actual combat (user login, Gorm database configuration is separated separately, Consul configuration is separated separately)

1. Copy the rbacManager.go and rbacManager folders under the server/rbac/proto folder to the proto folder in the client project 

2. Call the Rbac role addition, deletion, modification and query microservice

In the Index(), Add(), DoAdd(), Edit(), DoEdit(), Delete() methods of controllers/admin/ maanger.go , call the Rbac administrator to add, delete, modify and check the microservice function, which needs to be included in the import Introduce rbacRole, rbacManager microservice related packages, the code is as follows:

import (
    pbManager "goshop/proto/rbacManager"
	pbRole "goshop/proto/rbacRole"
)

The original controllers/admin/manager.go code is as follows: You can also refer to [golang gin framework] 14. Gin mall project-RBAC management

package admin

import (
	"github.com/gin-gonic/gin"
	"goshop/models"
	"net/http"
	"strings"
)

type ManagerController struct {
	BaseController
}

func (con ManagerController) Index(c *gin.Context) {
	//获取管理员列表,以及关联对应的角色
	managerList := []models.Manager{}
	models.DB.Preload("Role").Find(&managerList)

	c.HTML(http.StatusOK, "admin/manager/index.html", gin.H{
		"managerList": managerList,
	})
}

//添加管理员
func (con ManagerController) Add(c *gin.Context) {
	//获取角色
	roleList := []models.Role{}
	models.DB.Find(&roleList)
	c.HTML(http.StatusOK, "admin/manager/add.html", gin.H{
		"roleList": roleList,
	})
}

//添加管理员:提交
func (con ManagerController) DoAdd(c *gin.Context) {
	//获取角色id,判断是否合法
	roleId, err := models.Int(c.PostForm("role_id"))
	if err != nil {
		con.Error(c, "角色不合法", "/admin/manager/add")
		return
	}
	//获取提交的表单信息
	username := strings.Trim(c.PostForm("username"), " ")
	password := strings.Trim(c.PostForm("password"), " ")
	email := strings.Trim(c.PostForm("email"), " ")
	mobile := strings.Trim(c.PostForm("mobile"), " ")

	//判断用户名和密码是否符合要求
	if len(username) < 2 || len(password) < 6 {
		con.Error(c, "用户名或密码长度不合法", "/admin/manager/add")
		return
	}

	//判断管理员是否存在
	managerList := []models.Manager{}
	models.DB.Where("username = ?", username).Find(&managerList)
	if len(managerList) > 0 {
		con.Error(c, "管理员已存在", "/admin/manager/add")
		return
	}

	//实例化Manager,执行增加管理员
	manager := models.Manager{
		Username: username,
		Password: models.Md5(password),
		Email:    email,
		Mobile:   mobile,
		AddTime:  int(models.GetUnix()),
		RoleId:   roleId,
		Status:   1,
	}
	err = models.DB.Create(&manager).Error
	if err != nil {
		con.Error(c, "添加管理员失败", "/admin/manager/add")
		return
	}
	con.Success(c, "添加管理员成功", "/admin/manager")
}

//编辑管理员
func (con ManagerController) Edit(c *gin.Context) {
	//获取管理员
	id, err := models.Int(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/manager")
		return
	}
	manager := models.Manager{Id: id}
	models.DB.Find(&manager)

	if manager.Username == "" {
		con.Error(c, "管理员#" + models.String(id) + "不存在", "/admin/manager")
		return
	}
	//获取所有角色
	roleList := []models.Role{}
	models.DB.Find(&roleList)

	c.HTML(http.StatusOK, "admin/manager/edit.html", gin.H{
		"manager":  manager,
		"roleList": roleList,
	})
}

//编辑管理员提交
func (con ManagerController) DoEdit(c *gin.Context) {
	//获取管理员id,并判断
	id, err := models.Int(c.PostForm("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/manager")
		return
	}
	//获取角色id,并判断
	roleId, err2 := models.Int(c.PostForm("role_id"))
	if err2 != nil {
		con.Error(c, "传入数据错误", "/admin/manager")
		return
	}

	//获取提交的表单信息
	username := strings.Trim(c.PostForm("username"), " ")
	password := strings.Trim(c.PostForm("password"), " ")
	email := strings.Trim(c.PostForm("email"), " ")
	mobile := strings.Trim(c.PostForm("mobile"), " ")
	//执行修改
	manager := models.Manager{Id: id}
	models.DB.Find(&manager)
	manager.Username = username
	manager.Email = email
	manager.RoleId = roleId
	manager.Mobile = mobile
	//判断密码, 为空 表示不修改密码
	if password != "" {
		//判断密码长度
		if len(password) < 6 {
			con.Error(c, "密码长度不合法", "/admin/manager/edit?id" + models.String(id))
			return
		}
		manager.Password = models.Md5(password)
	}
	//保存
	err = models.DB.Save(&manager).Error
	if err != nil {
		con.Error(c, "修改数据失败", "/admin/manager/edit?id="+models.String(id))
		return
	}
	con.Success(c, "修改数据成功", "/admin/manager")
}

//删除
func (con ManagerController) Delete(c *gin.Context) {
	//获取提交的表单数据
	id, err := models.Int(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/manager")
		return
	}

	//查询管理员是否存在
	manager := models.Manager{Id: id}
	err = models.DB.Delete(&manager).Error
	if err != nil {
		con.Error(c, "删除数据失败", "/admin/manager")
		return
	}
	con.Success(c, "删除数据成功", "/admin/manager")
}

(1). Here we need to improve the UnixToTime() method in models/tool.go

The purpose is to return the corresponding time according to different types of timestamps passed in. The original method:

//时间戳转换成日期函数
func UnixToTime(timestamp int) string {
	t := time.Unix(int64(timestamp), 0)
	return t.Format("2006-01-02 15:04:05")
}

 The improved method:

//时间戳转换成日期函数
func UnixToTime(timestamp interface{}) string {
	value1, ok64 := timestamp.(int64)  //类型断言,判断传入的参数数据类型,并根据不同数据类型进行逻辑处理
	value2, ok32 := timestamp.(int32)
	value3, ok := timestamp.(int)
	if ok64 {
		t := time.Unix(value1, 0)
		return t.Format("2006-01-02 15:04:05")
	} else if ok32 {
		t := time.Unix(int64(value2), 0)
		return t.Format("2006-01-02 15:04:05")
	} else if ok {
		t := time.Unix(int64(value3), 0)
		return t.Format("2006-01-02 15:04:05")
	} else {
		return "time error"
	}
}

(2). The Index() method calls the microservice code

Original method:

func (con ManagerController) Index(c *gin.Context) {
	//获取管理员列表,以及关联对应的角色
	managerList := []models.Manager{}
	models.DB.Preload("Role").Find(&managerList)

	c.HTML(http.StatusOK, "admin/manager/index.html", gin.H{
		"managerList": managerList,
	})
}

The improved method:

func (con ManagerController) Index(c *gin.Context) {
	//调用Rbac微服务:获取管理员列表,以及关联对应的角色
	rbacClient := pbManager.NewRbacManagerService("rbac", models.RbacClient)
	res, _ := rbacClient.ManagerGet(context.Background(), &pbManager.ManagerGetRequest{})

	c.HTML(http.StatusOK, "admin/manager/index.html", gin.H{
		"managerList": res.ManagerList,
	})
}

(3).Add() method calls microservice code

Original method:

//添加管理员
func (con ManagerController) Add(c *gin.Context) {
	//获取角色
	roleList := []models.Role{}
	models.DB.Find(&roleList)
	c.HTML(http.StatusOK, "admin/manager/add.html", gin.H{
		"roleList": roleList,
	})
}

The improved method:

//添加管理员
func (con ManagerController) Add(c *gin.Context) {
	//获取所有的角色
	rbacClient := pbRole.NewRbacRoleService("rbac", models.RbacClient)
	res, _ := rbacClient.RoleGet(context.Background(), &pbRole.RoleGetRequest{})

	c.HTML(http.StatusOK, "admin/manager/add.html", gin.H{
		"roleList": res.RoleList,
	})
}

 (4). The DoAdd() method calls the microservice code

Original method:

//添加管理员:提交
func (con ManagerController) DoAdd(c *gin.Context) {
	//获取角色id,判断是否合法
	roleId, err := models.Int(c.PostForm("role_id"))
	if err != nil {
		con.Error(c, "角色不合法", "/admin/manager/add")
		return
	}
	//获取提交的表单信息
	username := strings.Trim(c.PostForm("username"), " ")
	password := strings.Trim(c.PostForm("password"), " ")
	email := strings.Trim(c.PostForm("email"), " ")
	mobile := strings.Trim(c.PostForm("mobile"), " ")

	//判断用户名和密码是否符合要求
	if len(username) < 2 || len(password) < 6 {
		con.Error(c, "用户名或密码长度不合法", "/admin/manager/add")
		return
	}

	//判断管理员是否存在
	managerList := []models.Manager{}
	models.DB.Where("username = ?", username).Find(&managerList)
	if len(managerList) > 0 {
		con.Error(c, "管理员已存在", "/admin/manager/add")
		return
	}

	//实例化Manager,执行增加管理员
	manager := models.Manager{
		Username: username,
		Password: models.Md5(password),
		Email:    email,
		Mobile:   mobile,
		AddTime:  int(models.GetUnix()),
		RoleId:   roleId,
		Status:   1,
	}
	err = models.DB.Create(&manager).Error
	if err != nil {
		con.Error(c, "添加管理员失败", "/admin/manager/add")
		return
	}
	con.Success(c, "添加管理员成功", "/admin/manager")
}

The improved method:

//添加管理员:提交
func (con ManagerController) DoAdd(c *gin.Context) {
	//获取角色id,判断是否合法
	roleId, err := models.Int(c.PostForm("role_id"))
	if err != nil {
		con.Error(c, "角色不合法", "/admin/manager/add")
		return
	}
	//获取提交的表单信息
	username := strings.Trim(c.PostForm("username"), " ")
	password := strings.Trim(c.PostForm("password"), " ")
	email := strings.Trim(c.PostForm("email"), " ")
	mobile := strings.Trim(c.PostForm("mobile"), " ")

	//判断用户名和密码是否符合要求
	if len(username) < 2 || len(password) < 6 {
		con.Error(c, "用户名或密码长度不合法", "/admin/manager/add")
		return
	}

	//判断管理员是否存在
	rbacClient := pbManager.NewRbacManagerService("rbac", models.RbacClient)
	res, _ := rbacClient.ManagerGet(context.Background(), &pbManager.ManagerGetRequest{
		Username: username,
	})

	if len(res.ManagerList) > 0 {
		con.Error(c, "此管理员已存在", "/admin/manager/add")
		return
	}

	//调用增加管理员微服务方法:执行增加管理员
	addResult, _ := rbacClient.ManagerAdd(context.Background(), &pbManager.ManagerAddRequest{
		Username: username,
		Password: models.Md5(password),
		Email:    email,
		Mobile:   mobile,
		RoleId:   int64(roleId),
		Status:   1,
		AddTime:  int64(models.GetUnix()),
	})

	if !addResult.Success {
		con.Error(c, "添加管理员失败", "/admin/manager/add")
		return
	}
	con.Success(c, "增加管理员成功", "/admin/manager")
}

 (5). The Edit() method calls the microservice code

Original method:

//编辑管理员
func (con ManagerController) Edit(c *gin.Context) {
	//获取管理员
	id, err := models.Int(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/manager")
		return
	}
	manager := models.Manager{Id: id}
	models.DB.Find(&manager)

	if manager.Username == "" {
		con.Error(c, "管理员#" + models.String(id) + "不存在", "/admin/manager")
		return
	}
	//获取所有角色
	roleList := []models.Role{}
	models.DB.Find(&roleList)

	c.HTML(http.StatusOK, "admin/manager/edit.html", gin.H{
		"manager":  manager,
		"roleList": roleList,
	})
}

The improved method:

//编辑管理员
func (con ManagerController) Edit(c *gin.Context) {
	//获取管理员
	id, err := models.Int(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/manager")
		return
	}
	//通过管理员微服务获取管理员
	//获取管理员
	managerClient := pbManager.NewRbacManagerService("rbac", models.RbacClient)
	resManager, _ := managerClient.ManagerGet(context.Background(), &pbManager.ManagerGetRequest{
		Id: int64(id),
	})

	if len(resManager.ManagerList) <= 0  {
		con.Error(c, "管理员#" + models.String(id) + "不存在", "/admin/manager")
		return
	}

	//获取所有的角色
	roleClient := pbRole.NewRbacRoleService("rbac", models.RbacClient)
	resRole, _ := roleClient.RoleGet(context.Background(), &pbRole.RoleGetRequest{})

	c.HTML(http.StatusOK, "admin/manager/edit.html", gin.H{
		"manager":  resManager.ManagerList[0],
		"roleList": resRole.RoleList,
	})
}

(6). The DoEdit() method calls the microservice code

Original method:

//编辑管理员提交
func (con ManagerController) DoEdit(c *gin.Context) {
	//获取管理员id,并判断
	id, err := models.Int(c.PostForm("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/manager")
		return
	}
	//获取角色id,并判断
	roleId, err2 := models.Int(c.PostForm("role_id"))
	if err2 != nil {
		con.Error(c, "传入数据错误", "/admin/manager")
		return
	}

	//获取提交的表单信息
	username := strings.Trim(c.PostForm("username"), " ")
	password := strings.Trim(c.PostForm("password"), " ")
	email := strings.Trim(c.PostForm("email"), " ")
	mobile := strings.Trim(c.PostForm("mobile"), " ")
	//执行修改
	manager := models.Manager{Id: id}
	models.DB.Find(&manager)
	manager.Username = username
	manager.Email = email
	manager.RoleId = roleId
	manager.Mobile = mobile
	//判断密码, 为空 表示不修改密码
	if password != "" {
		//判断密码长度
		if len(password) < 6 {
			con.Error(c, "密码长度不合法", "/admin/manager/edit?id" + models.String(id))
			return
		}
		manager.Password = models.Md5(password)
	}
	//保存
	err = models.DB.Save(&manager).Error
	if err != nil {
		con.Error(c, "修改数据失败", "/admin/manager/edit?id="+models.String(id))
		return
	}
	con.Success(c, "修改数据成功", "/admin/manager")
}

The improved method:

//编辑管理员提交
func (con ManagerController) DoEdit(c *gin.Context) {
	//获取管理员id,并判断
	id, err := models.Int(c.PostForm("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/manager")
		return
	}
	//获取角色id,并判断
	roleId, err2 := models.Int(c.PostForm("role_id"))
	if err2 != nil {
		con.Error(c, "传入数据错误", "/admin/manager")
		return
	}

	//获取提交的表单信息
	username := strings.Trim(c.PostForm("username"), " ")
	password := strings.Trim(c.PostForm("password"), " ")
	email := strings.Trim(c.PostForm("email"), " ")
	mobile := strings.Trim(c.PostForm("mobile"), " ")
	//执行修改
	//判断电话号码是否合法
	if len(mobile) > 11 {
		con.Error(c, "mobile长度不合法", "/admin/manager/edit?id="+models.String(id))
		return
	}
	//注意:判断密码是否为空 为空表示不修改密码 不为空表示修改密码
	if password != "" {
		//判断密码长度是否合法
		if len(password) < 6 {
			con.Error(c, "密码的长度不合法 密码长度不能小于6位", "/admin/manager/edit?id="+models.String(id))
			return
		}
		password = models.Md5(password)
	}

	//调用管理员修改微服务方法进行修改
	managerClient := pbManager.NewRbacManagerService("rbac", models.RbacClient)
	editResult, _ := managerClient.ManagerEdit(context.Background(), &pbManager.ManagerEditRequest{
		Id:       int64(id),
		Username: username,
		Password: password,
		Email:    email,
		Mobile:   mobile,
		RoleId:   int64(roleId),
	})
	if !editResult.Success {
		con.Error(c, "修改数据失败", "/admin/manager/edit?id="+models.String(id))
		return
	}
	con.Success(c, "修改数据成功", "/admin/manager")
}

(7).Delete() method calls microservice code

Original method:

//删除
func (con ManagerController) Delete(c *gin.Context) {
	//获取提交的表单数据
	id, err := models.Int(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/manager")
		return
	}

	//查询管理员是否存在
	manager := models.Manager{Id: id}
	err = models.DB.Delete(&manager).Error
	if err != nil {
		con.Error(c, "删除数据失败", "/admin/manager")
		return
	}
	con.Success(c, "删除数据成功", "/admin/manager")
}

The improved method:

//删除
func (con ManagerController) Delete(c *gin.Context) {
	//获取提交的表单数据
	id, err := models.Int(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/manager")
		return
	}
	//查询管理员是否存在
	//获取管理员
	managerClient := pbManager.NewRbacManagerService("rbac", models.RbacClient)
	resManager, _ := managerClient.ManagerGet(context.Background(), &pbManager.ManagerGetRequest{
		Id: int64(id),
	})

	if len(resManager.ManagerList) <= 0  {
		con.Error(c, "管理员#" + models.String(id) + "不存在", "/admin/manager")
		return
	}

	//调用管理员删除方法进行删除
	managerDeleteClient := pbManager.NewRbacManagerService("rbac", models.RbacClient)
	managerRes, _ := managerDeleteClient.ManagerDelete(context.Background(), &pbManager.ManagerDeleteRequest{
		Id: int64(id),
	})
	if managerRes.Success {
		con.Success(c, "删除数据成功", "/admin/manager")
		return
	}
	con.Success(c, "删除数据失败", "/admin/manager")
}

(8). The complete code is as follows

package admin

import (
	"github.com/gin-gonic/gin"
	"goshop/models"
	pbRole "goshop/proto/rbacRole"
	"net/http"
	"strings"
	"context"
	 pbManager "goshop/proto/rbacManager"
)

type ManagerController struct {
	BaseController
}

func (con ManagerController) Index(c *gin.Context) {
	//调用Rbac微服务:获取管理员列表,以及关联对应的角色
	rbacClient := pbManager.NewRbacManagerService("rbac", models.RbacClient)
	res, _ := rbacClient.ManagerGet(context.Background(), &pbManager.ManagerGetRequest{})

	c.HTML(http.StatusOK, "admin/manager/index.html", gin.H{
		"managerList": res.ManagerList,
	})

}

//添加管理员
func (con ManagerController) Add(c *gin.Context) {
	//获取所有的角色
	rbacClient := pbRole.NewRbacRoleService("rbac", models.RbacClient)
	res, _ := rbacClient.RoleGet(context.Background(), &pbRole.RoleGetRequest{})

	c.HTML(http.StatusOK, "admin/manager/add.html", gin.H{
		"roleList": res.RoleList,
	})
}

//添加管理员:提交
func (con ManagerController) DoAdd(c *gin.Context) {
	//获取角色id,判断是否合法
	roleId, err := models.Int(c.PostForm("role_id"))
	if err != nil {
		con.Error(c, "角色不合法", "/admin/manager/add")
		return
	}
	//获取提交的表单信息
	username := strings.Trim(c.PostForm("username"), " ")
	password := strings.Trim(c.PostForm("password"), " ")
	email := strings.Trim(c.PostForm("email"), " ")
	mobile := strings.Trim(c.PostForm("mobile"), " ")

	//判断用户名和密码是否符合要求
	if len(username) < 2 || len(password) < 6 {
		con.Error(c, "用户名或密码长度不合法", "/admin/manager/add")
		return
	}

	//判断管理员是否存在
	rbacClient := pbManager.NewRbacManagerService("rbac", models.RbacClient)
	res, _ := rbacClient.ManagerGet(context.Background(), &pbManager.ManagerGetRequest{
		Username: username,
	})

	if len(res.ManagerList) > 0 {
		con.Error(c, "此管理员已存在", "/admin/manager/add")
		return
	}

	//调用增加管理员微服务方法:执行增加管理员
	addResult, _ := rbacClient.ManagerAdd(context.Background(), &pbManager.ManagerAddRequest{
		Username: username,
		Password: models.Md5(password),
		Email:    email,
		Mobile:   mobile,
		RoleId:   int64(roleId),
		Status:   1,
		AddTime:  int64(models.GetUnix()),
	})

	if !addResult.Success {
		con.Error(c, "添加管理员失败", "/admin/manager/add")
		return
	}
	con.Success(c, "增加管理员成功", "/admin/manager")
}

//编辑管理员
func (con ManagerController) Edit(c *gin.Context) {
	//获取管理员
	id, err := models.Int(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/manager")
		return
	}
	//通过管理员微服务获取管理员
	//获取管理员
	managerClient := pbManager.NewRbacManagerService("rbac", models.RbacClient)
	resManager, _ := managerClient.ManagerGet(context.Background(), &pbManager.ManagerGetRequest{
		Id: int64(id),
	})

	if len(resManager.ManagerList) <= 0  {
		con.Error(c, "管理员#" + models.String(id) + "不存在", "/admin/manager")
		return
	}

	//获取所有的角色
	roleClient := pbRole.NewRbacRoleService("rbac", models.RbacClient)
	resRole, _ := roleClient.RoleGet(context.Background(), &pbRole.RoleGetRequest{})

	c.HTML(http.StatusOK, "admin/manager/edit.html", gin.H{
		"manager":  resManager.ManagerList[0],
		"roleList": resRole.RoleList,
	})
}

//编辑管理员提交
func (con ManagerController) DoEdit(c *gin.Context) {
	//获取管理员id,并判断
	id, err := models.Int(c.PostForm("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/manager")
		return
	}
	//获取角色id,并判断
	roleId, err2 := models.Int(c.PostForm("role_id"))
	if err2 != nil {
		con.Error(c, "传入数据错误", "/admin/manager")
		return
	}

	//获取提交的表单信息
	username := strings.Trim(c.PostForm("username"), " ")
	password := strings.Trim(c.PostForm("password"), " ")
	email := strings.Trim(c.PostForm("email"), " ")
	mobile := strings.Trim(c.PostForm("mobile"), " ")
	//执行修改
	//判断电话号码是否合法
	if len(mobile) > 11 {
		con.Error(c, "mobile长度不合法", "/admin/manager/edit?id="+models.String(id))
		return
	}
	//注意:判断密码是否为空 为空表示不修改密码 不为空表示修改密码
	if password != "" {
		//判断密码长度是否合法
		if len(password) < 6 {
			con.Error(c, "密码的长度不合法 密码长度不能小于6位", "/admin/manager/edit?id="+models.String(id))
			return
		}
		password = models.Md5(password)
	}

	//调用管理员修改微服务方法进行修改
	managerClient := pbManager.NewRbacManagerService("rbac", models.RbacClient)
	editResult, _ := managerClient.ManagerEdit(context.Background(), &pbManager.ManagerEditRequest{
		Id:       int64(id),
		Username: username,
		Password: password,
		Email:    email,
		Mobile:   mobile,
		RoleId:   int64(roleId),
	})
	if !editResult.Success {
		con.Error(c, "修改数据失败", "/admin/manager/edit?id="+models.String(id))
		return
	}
	con.Success(c, "修改数据成功", "/admin/manager")
}

//删除
func (con ManagerController) Delete(c *gin.Context) {
	//获取提交的表单数据
	id, err := models.Int(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/manager")
		return
	}
	//查询管理员是否存在
	//获取管理员
	managerClient := pbManager.NewRbacManagerService("rbac", models.RbacClient)
	resManager, _ := managerClient.ManagerGet(context.Background(), &pbManager.ManagerGetRequest{
		Id: int64(id),
	})

	if len(resManager.ManagerList) <= 0  {
		con.Error(c, "管理员#" + models.String(id) + "不存在", "/admin/manager")
		return
	}

	//调用管理员删除方法进行删除
	managerDeleteClient := pbManager.NewRbacManagerService("rbac", models.RbacClient)
	managerRes, _ := managerDeleteClient.ManagerDelete(context.Background(), &pbManager.ManagerDeleteRequest{
		Id: int64(id),
	})
	if managerRes.Success {
		con.Success(c, "删除数据成功", "/admin/manager")
		return
	}
	con.Success(c, "删除数据失败", "/admin/manager")
}

 3. Verify authority management Rbac administrator adds, deletes, modifies and checks microservice functions

1. Start the server first

See [ golang gin framework] 40. Gin mall project - Captcha verification code microservice code in microservice combat , here also start the verification code captcha microservice server code and authority management Rbac microservice ( user login microservice server, role Manage the microservice server, the administrator manages the microservice server) server

2. Start the client

Run in the project root directory: go run main.go to start the project

3. Verify authority management Rbac administrator adds, deletes, modifies and checks whether the microservice operation is successful 

Visit the background login page, enter the user name, password, verification code, log in to the background, enter the administrator management page, and add, delete, modify and check the administrator

 Well, the authority management Rbac administrator adds, deletes, modifies, and checks the microservice function. The client operation is completed. Here, the server and client functions of the microservice operation are roughly [golang gin framework] 42. Gin mall project-background Rbac microservice Role addition, deletion, modification, and query are similar to microservices . You can refer to this article for operation. The next section will continue to explain the addition, deletion, modification, and query of permissions for authority management Rbac microservices

[Previous section] [golang gin framework] 42. Gin mall project - after the actual combat of microservices, background Rbac microservice roles add, delete, modify and check microservices

[Next section] [golang gin framework] 44. Gin mall project - adding, deleting, modifying and checking microservices for permissions of background Rbac microservices after actual combat of microservices

Guess you like

Origin blog.csdn.net/zhoupenghui168/article/details/131968316