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

 1. Refactor the background Rbac user login microservice function

The previous section explained the user login function of the background Rbac microservice and the separate extraction of the Gorm database configuration, and the separate extraction of the Consul configuration . This section explains the addition, deletion, modification, and query of the background Rbac microservice role. Service and background Rbac user login microservices are different sub-microservice functions belonging to the same Rbac microservice . In order to distinguish different sub-microservice functions, before adding, deleting, modifying and checking microservice functions for background Rbac microservice roles , it is necessary to In the previous section, Rbac users log in to microservices for refactoring

 1. Re-improved the rbac.proto under the proto folder

Rename rbac.proto to rbacLogin.proto , and modify option go_package , go_package = " ./proto/rbacLogin ", service Rbac should be service RbacLogin , and other codes remain unchanged. The complete code is as follows:

syntax = "proto3";

package rbac;

option go_package = "./proto/rbacLogin";

service RbacLogin {
    //登录操作
	rpc Login(LoginRequest) returns (LoginResponse) {}
}

//用户信息model:参考models/manager.go,一一对应
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;
}

//登录请求参数
message LoginRequest{
	string username=1;
	string password=2;
}

//登录返回参数
message LoginResponse{
	bool isLogin=1;
	repeated ManagerModel userlist=2;  //因为在client端需要返回用户相关信息,故定义一个切片
}

2. Delete the rbac folder generated by proto

3. Execute protoc --proto_path=. --micro_out=. --go_out=:.proto/rbacLogin.proto to generate the corresponding rbacLgin folder

4. Modify rbac.go under the handler folder

Change the rbac.go file name to rbacLigin.go , and change pb "rbac/proto/rbac" to pb "rbac/proto/rbacLogin" and type Rbac struct{} to type RbacLogin struct{}. The complete code is as follows :

package handler

import (
	"context"
	"rbac/models"
	pb "rbac/proto/rbacLogin"
)

type RbacLogin struct{}

//后台用户登录的微服务
func (e *RbacLogin) Login(ctx context.Context, req *pb.LoginRequest, res *pb.LoginResponse) error {
	managerList := []models.Manager{}
	err := models.DB.Where("username=? AND password=?", req.Username, req.Password).Find(&managerList).Error

	//处理数据
	var templist []*pb.ManagerModel
	for i := 0; i < len(managerList); i++ {
		templist = append(templist, &pb.ManagerModel{
			Id:       int64(managerList[i].Id),
			Username: managerList[i].Username,
			Password: managerList[i].Password,
			Mobile:   managerList[i].Mobile,
			Email:    managerList[i].Email,
			Status:   int64(managerList[i].Status),
			RoleId:   int64(managerList[i].RoleId),
			AddTime:  int64(managerList[i].AddTime),
			IsSuper:  int64(managerList[i].IsSuper),
		})
	}
	if len(managerList) > 0 {
		res.IsLogin = true
	} else {
		res.IsLogin = false
	}
	res.Userlist = templist

	return err
}

 5. Improve main.go

Change pb "rbac/proto/rbac" in main.go to pb "rbac/proto/rbacLogin", and the following

pb.RegisterRbacHandler ( srv.Server (), new(handler.Rbac ) ) is changed to pb.RegisterRbacLoginHandler ( srv.Server(), new(handler.RbacLogin)) , the complete code is as follows:

package main

import (
	"rbac/handler"
	"rbac/models"
	pb "rbac/proto/rbacLogin"
	"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)
	}
	// Run service
	if err := srv.Run(); err != nil {
		logger.Fatal(err)
	}
}

  

 6. Run the microservice to see if the modification reports an error

 7. Improve client microservices

Delete the rbac.proto file and the rbac folder in the proto folder of the project under the client , and copy the rbacLogin.go and rbacLogin folders under server/rbac/proto to the proto folder in the project under the client

8. Modify the code that calls the proto/rbac microservice interface

Here only the microservice code for rbac login is called under controllers/login.go, so change pbRbac "goshop/proto/rbac" to pbRbac "goshop/proto/rbacLogin " , and change pbRbac.NewRbacService to pbRbac.NewRbacLoginService

 9. Verify that the Rbac user login microservice operation is successful

2. Realize background authority management Rbac role addition, deletion, modification and query microservices

1. Create a Role model

To add, delete, modify and check roles, you need to create a corresponding model, so create a role.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 Role struct { // 结构体首字母大写, 和数据库表名对应, 默认访问数据表users, 可以设置访问数据表的方法
	Id  int
	Title string
	Description string
	Status int
	AddTime int
}

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

 2. Create rbacRole.proto under the proto folder

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

syntax = "proto3";

package rbac;

option go_package = "./proto/rbacRole";

//角色管理
service RbacRole {
    //获取角色rpc方法: 请求参数RoleGetRequest, 响应参数RoleGetResponse
	rpc RoleGet(RoleGetRequest) returns (RoleGetResponse) {}
	//增加角色rpc方法: 请求参数RoleAddRequest, 响应参数RoleAddResponse
	rpc RoleAdd(RoleAddRequest) returns (RoleAddResponse) {}
	//编辑角色rpc方法: 请求参数RoleEditRequest, 响应参数RoleEditResponse
	rpc RoleEdit(RoleEditRequest) returns (RoleEditResponse) {}
	//删除角色rpc方法: 请求参数RoleDeleteRequest, 响应参数RoleDeleteResponse
	rpc RoleDelete(RoleDeleteRequest) returns (RoleDeleteResponse) {}
}

//角色相关model
message RoleModel{
	int64 id=1;
	string title=2;
	string description=3;
	int64 status=4;
	int64 addTime =5;
}

//获取角色请求参数
message RoleGetRequest{
    //角色id
	int64 id =1;
}

//获取角色响应参数
message RoleGetResponse{
    //角色model切片
	repeated RoleModel roleList=1;
}

//增加角色请求参数
message RoleAddRequest{
    //角色名称
	string title=1;
	//说明
	string description=2;
	//状态
	int64 status=3;
	//增加时间
	int64 addTime =4;
}

//增加角色响应参数
message RoleAddResponse{
    //是否增加成功
	bool success=1;
	//返回状态说明
	string message=2;
}

//编辑角色请求参数
message RoleEditRequest{
    //角色id
	int64 id=1;
	//角色名称
	string title=2;
	//说明
	string description=3;
	//状态
	int64 status=4;
	//增加时间
	int64 addTime =5;
}

//编辑角色响应参数
message RoleEditResponse{	
	//是否编辑成功
    bool success=1;
    //返回状态说明
    string message=2;
}

//删除角色请求参数
message RoleDeleteRequest{
	//角色id
	int64 id=1;
}

//删除角色响应参数
message RoleDeleteResponse{	
	//是否删除成功
    bool success=1;
    //返回状态说明
    string message=2;
}

3. Generate role-related pb.go, pb.micro.go files

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

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

Refer to [golang gin framework] 14. Add, delete, modify and check Gin mall project-RBAC management_role , the specific rbacRole.go code is as follows:

package handler

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

type RbacRole struct{}

//获取角色
func (e *RbacRole) RoleGet(ctx context.Context, req *pb.RoleGetRequest, res *pb.RoleGetResponse) error {
	roleList := []models.Role{}
	where := "1=1"
	if req.Id > 0 {  // 当传入角色id时,获取对应的角色数据, 当没有传入角色id时,获取角色列表数据
		where += " AND id=" + strconv.Itoa(int(req.Id))
	}
	models.DB.Where(where).Find(&roleList)

	//处理数据
	var tempList []*pb.RoleModel
	for _, v := range roleList {
		tempList = append(tempList, &pb.RoleModel{
			Id:          int64(v.Id),
			Title:       v.Title,
			Description: v.Description,
			Status:      int64(v.Status),
			AddTime:     int64(v.AddTime),
		})
	}

	res.RoleList = tempList
	return nil
}

//增加角色
func (e *RbacRole) RoleAdd(ctx context.Context, req *pb.RoleAddRequest, res *pb.RoleAddResponse) error {
	role := models.Role{}
	role.Title = req.Title
	role.Description = req.Description
	role.Status = int(req.Status)
	role.AddTime = int(req.AddTime)

	err := models.DB.Create(&role).Error
	if err != nil {
		res.Success = false
		res.Message = "增加数据失败"
	} else {
		res.Success = true
		res.Message = "增加数据成功"
	}
	return err
}

//修改角色
func (e *RbacRole) RoleEdit(ctx context.Context, req *pb.RoleEditRequest, res *pb.RoleEditResponse) error {
	role := models.Role{Id: int(req.Id)}
	models.DB.Find(&role)
	role.Title = req.Title
	role.Description = req.Description

	err := models.DB.Save(&role).Error
	if err != nil {
		res.Success = false
		res.Message = "修改数据失败"
	} else {
		res.Success = true
		res.Message = "修改数据成功"
	}

	return nil
}

//删除角色
func (e *RbacRole) RoleDelete(ctx context.Context, req *pb.RoleDeleteRequest, res *pb.RoleDeleteResponse) error {
	role := models.Role{Id: int(req.Id)}
	err := models.DB.Delete(&role).Error
	if err != nil {
		res.Success = false
		res.Message = "删除数据失败"
	} else {
		res.Success = true
		res.Message = "删除数据成功"
	}
	return nil
}

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

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

// Register handler:注册角色微服务
	if err := pbRole.RegisterRbacRoleHandler(srv.Server(), new(handler.RbacRole)); 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"
	"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)
	}
	// Run service
	if err := srv.Run(); err != nil {
		logger.Fatal(err)
	}
}

6. Realize the Rbac role client microservice function

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

(1). Copy the rbacRole.go and rbacRole 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(), DoAdd(), DoEdit(), Delete() methods of controllers/admin/role.go, call the Rbac role addition, deletion, modification and query microservice function

The original controllers/admin/role.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 RoleController struct {
	BaseController
}

//角色列表
func (con RoleController) Index(c *gin.Context) {
	//定义一个角色切片
	roleList := []models.Role{}
	//获取角色
	models.DB.Find(&roleList)
	c.HTML(http.StatusOK, "admin/role/index.html", gin.H{
		"roleList": roleList,
	})
}

//新增角色
func (con RoleController) Add(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/role/add.html", gin.H{})
}

//新增角色:提交
func (con RoleController) DoAdd(c *gin.Context) {
	//获取表单的提交数据
	//strings.Trim(str, cutset), 去除字符串两边的cutset字符
	title := strings.Trim(c.PostForm("title"), " ") // 去除字符串两边的空格
	description := strings.Trim(c.PostForm("description"), " ")

	//判断角色名称是否为空
	if title == "" {
		con.Error(c, "角色名称不能为空", "/admin/role/add")
		return
	}
	//给角色模型赋值,并保存数据到数据库
	role := models.Role{}
	role.Title = title
	role.Description = description
	role.Status = 1
	role.AddTime = int(models.GetUnix())
	err := models.DB.Create(&role).Error
	if err != nil {
		con.Error(c, "增加角色失败,请重试", "/admin/role/add")
		return
	}
	con.Success(c, "增加角色成功", "/admin/role")
}

//编辑角色
func (con RoleController) Edit(c *gin.Context) {
	//获取角色id
	id, err := models.Int(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
	} else {
		role := models.Role{Id: id}
		models.DB.Find(&role)
		c.HTML(http.StatusOK, "admin/role/edit.html", gin.H{
			"role": role,
		})
	}
}

//编辑角色:提交
func (con RoleController) DoEdit(c *gin.Context) {
	//获取提交的表单数据
	id, err := models.Int(c.PostForm("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
		return
	}
	//获取表单的提交数据
	//strings.Trim(str, cutset), 去除字符串两边的cutset字符
	title := strings.Trim(c.PostForm("title"), " ") // 去除字符串两边的空格
	description := strings.Trim(c.PostForm("description"), " ")
	//判断角色名称是否为空
	if title == "" {
		con.Error(c, "角色名称不能为空", "/admin/role/add")
		return
	}
	//查询角色是否存在
	role := models.Role{Id: id}
	models.DB.Find(&role)

	//修改角色属性
	role.Title = title
	role.Description = description
	err = models.DB.Save(&role).Error
	if err != nil {
		con.Error(c, "修改数据失败", "/admin/role/edit?id="+models.String(id))
		return
	}
	con.Success(c, "修改数据成功", "/admin/role")
}

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

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

//授权
func (con RoleController) Auth(c *gin.Context) {
	//获取id
	id, err := models.Int(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
		return
	}
	role := models.Role{Id: id}
	models.DB.Find(&role)

	//获取所有权限列表
	accessList := []models.Access{}
	models.DB.Where("module_id = ?", 0).Preload("AccessItem").Find(&accessList)

	//获取当前角色拥有的权限,并把权限id放在一个map对象中
	roleAccess := []models.RoleAccess{}
	models.DB.Where("role_id = ?", id).Find(&roleAccess)
	roleAccessMap := make(map[int]int)
	for _, v := range roleAccess {
		roleAccessMap[v.AccessId] = v.AccessId
	}

	//循环遍历所有权限数据,判断当前权限的id是否在角色权限的map对象中,如果是的话给当前数据加入checked属性
	for i := 0; i < len(accessList); i++ { //循环权限列表
		if _, ok := roleAccessMap[accessList[i].Id]; ok { // 判断当前权限是否在角色权限的map对象中
			accessList[i].Checked = true
		}
		for j := 0; j < len(accessList[i].AccessItem); j++ { // 判断当前权限的子栏位是否在角色权限的map中
			if _, ok := roleAccessMap[accessList[i].AccessItem[j].Id]; ok { // 判断当前权限是否在角色权限的map对象中
				accessList[i].AccessItem[j].Checked = true
			}
		}
	}
	c.HTML(http.StatusOK, "admin/role/auth.html", gin.H{
		"roleId":     id,
		"accessList": accessList,
	})
}

//授权提交
func (con RoleController) DoAuth(c *gin.Context) {
	//获取提交的表单数据
	roleId, err := models.Int(c.PostForm("role_id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
		return
	}
	//获取表单提交的权限id切片
	accessIds := c.PostFormArray("access_node[]")
	//先删除当前角色对应的权限
	roleAccess := models.RoleAccess{}
	models.DB.Where("role_id = ?", roleId).Delete(&roleAccess)

	//循环遍历accessIds,增加当前角色对应的权限
	for _, v := range accessIds {
		roleAccess.RoleId = roleId
		accessId, _ := models.Int(v)
		roleAccess.AccessId = accessId
		models.DB.Create(&roleAccess)
	}

	con.Success(c, "角色授权成功", "/admin/role")
}

 After calling the Rbac role addition, deletion, modification and query microservice, the code is as follows:

package admin

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

type RoleController struct {
	BaseController
}

//角色列表
func (con RoleController) Index(c *gin.Context) {
	//调用Rbac微服务
	rbacClient := pbRbac.NewRbacRoleService("rbac", models.RbacClient)
	res, _ := rbacClient.RoleGet(context.Background(), &pbRbac.RoleGetRequest{})

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

//新增角色
func (con RoleController) Add(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/role/add.html", gin.H{})
}

//新增角色:提交
func (con RoleController) DoAdd(c *gin.Context) {
	//获取表单的提交数据
	//strings.Trim(str, cutset), 去除字符串两边的cutset字符
	title := strings.Trim(c.PostForm("title"), " ") // 去除字符串两边的空格
	description := strings.Trim(c.PostForm("description"), " ")

	//判断角色名称是否为空
	if title == "" {
		con.Error(c, "角色名称不能为空", "/admin/role/add")
		return
	}

	//调用微服务,实现角色的添加
	rbacClient := pbRbac.NewRbacRoleService("rbac", models.RbacClient)
	res, _ := rbacClient.RoleAdd(context.Background(), &pbRbac.RoleAddRequest{
		Title:       title,
		Description: description,
		AddTime:     models.GetUnix(),
		Status:      1,
	})
	if !res.Success {
		con.Error(c, "增加角色失败 请重试", "/admin/role/add")
	} else {
		con.Success(c, "增加角色成功", "/admin/role")
	}
}

//编辑角色
func (con RoleController) Edit(c *gin.Context) {
	//获取角色id
	id, err := models.Int(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
	} else {
		//调用微服务,获取角色信息
		rbacClient := pbRbac.NewRbacRoleService("rbac", models.RbacClient)
		res, _ := rbacClient.RoleGet(context.Background(), &pbRbac.RoleGetRequest{
			Id: int64(id),
		})
		c.HTML(http.StatusOK, "admin/role/edit.html", gin.H{
			"role": res.RoleList[0],
		})
	}
}

//编辑角色:提交
func (con RoleController) DoEdit(c *gin.Context) {
	//获取提交的表单数据
	id, err := models.Int(c.PostForm("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
		return
	}
	//获取表单的提交数据
	//strings.Trim(str, cutset), 去除字符串两边的cutset字符
	title := strings.Trim(c.PostForm("title"), " ") // 去除字符串两边的空格
	description := strings.Trim(c.PostForm("description"), " ")
	//判断角色名称是否为空
	if title == "" {
		con.Error(c, "角色名称不能为空", "/admin/role/add")
		return
	}
	//调用微服务修改
	rbacClient := pbRbac.NewRbacRoleService("rbac", models.RbacClient)
	res, _ := rbacClient.RoleEdit(context.Background(), &pbRbac.RoleEditRequest{
		Id:          int64(id),
		Title:       title,
		Description: description,
	})
	if !res.Success {
		con.Error(c, "修改数据失败", "/admin/role/edit?id="+models.String(id))
		return
	}
	con.Success(c, "修改数据成功", "/admin/role")
}

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

	rbacClient := pbRbac.NewRbacRoleService("rbac", models.RbacClient)
	res, _ := rbacClient.RoleDelete(context.Background(), &pbRbac.RoleDeleteRequest{
		Id: int64(id),
	})
	if res.Success {
		con.Success(c, "删除数据成功", "/admin/role")
		return
	}
	con.Error(c, "删除数据失败", "/admin/role")
}

//授权
func (con RoleController) Auth(c *gin.Context) {
	//获取id
	id, err := models.Int(c.Query("id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
		return
	}
	role := models.Role{Id: id}
	models.DB.Find(&role)

	//获取所有权限列表
	accessList := []models.Access{}
	models.DB.Where("module_id = ?", 0).Preload("AccessItem").Find(&accessList)

	//获取当前角色拥有的权限,并把权限id放在一个map对象中
	roleAccess := []models.RoleAccess{}
	models.DB.Where("role_id = ?", id).Find(&roleAccess)
	roleAccessMap := make(map[int]int)
	for _, v := range roleAccess {
		roleAccessMap[v.AccessId] = v.AccessId
	}

	//循环遍历所有权限数据,判断当前权限的id是否在角色权限的map对象中,如果是的话给当前数据加入checked属性
	for i := 0; i < len(accessList); i++ { //循环权限列表
		if _, ok := roleAccessMap[accessList[i].Id]; ok { // 判断当前权限是否在角色权限的map对象中
			accessList[i].Checked = true
		}
		for j := 0; j < len(accessList[i].AccessItem); j++ { // 判断当前权限的子栏位是否在角色权限的map中
			if _, ok := roleAccessMap[accessList[i].AccessItem[j].Id]; ok { // 判断当前权限是否在角色权限的map对象中
				accessList[i].AccessItem[j].Checked = true
			}
		}
	}
	c.HTML(http.StatusOK, "admin/role/auth.html", gin.H{
		"roleId":     id,
		"accessList": accessList,
	})
}

//授权提交
func (con RoleController) DoAuth(c *gin.Context) {
	//获取提交的表单数据
	roleId, err := models.Int(c.PostForm("role_id"))
	if err != nil {
		con.Error(c, "传入数据错误", "/admin/role")
		return
	}
	//获取表单提交的权限id切片
	accessIds := c.PostFormArray("access_node[]")
	//先删除当前角色对应的权限
	roleAccess := models.RoleAccess{}
	models.DB.Where("role_id = ?", roleId).Delete(&roleAccess)

	//循环遍历accessIds,增加当前角色对应的权限
	for _, v := range accessIds {
		roleAccess.RoleId = roleId
		accessId, _ := models.Int(v)
		roleAccess.AccessId = accessId
		models.DB.Create(&roleAccess)
	}

	con.Success(c, "角色授权成功", "/admin/role")
}

3. Verify authority management Rbac microservice function

1. Start the server first

See [golang gin framework] 40. Gin mall project - Captcha verification code microservice code for microservice combat, here you need to start the verification code captcha microservice server code and the Rbac user login microservice server code.

2. Start the client

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


3. Check whether the authority management Rbac role addition, deletion and modification 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 role management page, add, delete, modify and check the role

 

 

 Well, the authority management Rbac role addition, deletion, modification, and query microservice function client operation is completed. Here, the server and client functions of the microservice operation are roughly the same as [golang gin framework] 41. Gin mall project - background Rbac microservice after actual combat (user login, Gorm database configuration separate extraction, Consul configuration separate extraction) similar, you can refer to this article for operation, the following section continues to explain the addition, deletion, modification and query of authority management Rbac microservice administrators and the association between administrators and roles

[Previous section] R[golang gin framework] 41. Gin mall project - background Rbac microservice after microservice actual combat (user login, Gorm database configuration and Consul configuration are separately extracted) [Next section] [  golang gin Framework] 43. Gin mall project - adding, deleting, modifying and checking administrators of Rbac microservices in the background after actual combat of microservices, as well as association between administrators and roles

Guess you like

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