SoFunction
Updated on 2025-05-23

Project Practice of Golang to Implement Dynamic Routing

1. Dynamic routing

1. Structure (definition of database)

Contains the role database, menu database, role and menu relationship tables.

type Role struct {
	
	Rolename  string `json:"rolename"`
	Authority string `json:"authority"`
	Order     int    `json:"order" gorm:"column:order"`
	Status    bool   `json:"status"`
	Menus     []Menu `json:"menus" gorm:"many2many:role_menu_table"`
	Remark    string `json:"remark"`
}
type Menu struct {
	
	ParentID  uint   `json:"parentid" gorm:"column:parentid"`
	Path      string `json:"path"`
	Name      string `json:"name"`
	Component string `json:"component"`
	Sort      int    `json:"sort"`
	Meta      `json:"meta"`
	Children  []Menu `json:"children" gorm:"-"`
	Roles     []Role `json:"rolse" gorm:"many2many:role_menu_table"`
}

type Meta struct {
	ActiveName  string `json:"activeName" gorm:"comment: Highlight menu"`
	KeepAlive   bool   `json:"keepalive" gorm:"comment: Whether to cache"`           // Whether to cache	DefaultMenu bool   `json:"defaultmenu" gorm:"Comment: Is it the basic routing (under development)"` // Is it the basic routing (under development)	Title       string `json:"title" gorm:"comment: menu name"`                // Menu name	Icon        string `json:"icon" gorm:"comment: Menu icon"`                // Menu icon	CloseTab    bool   `json:"closeTab" gorm:"comment: Automatically close tab"`         // Automatically close tab}
type RoleMenu struct {
	MenuId string `json:"menuid" gorm:"colume:menuid"`
	RoleId string `json:"roleid" gorm:"colume:roleid"`
}

2. Preload preload

var role Role
err = ("Menus").Find(&role,roleid).Error
if err != nil {
	("Error:", err)
	return
}else{
    ("Role's Menus: %+v\n", )
}

Preload("Menus"): InquiryRoleWhen preloadedMenusFields, that is, queryRole All corresponding Menudata. In this way, you can avoid accessingWhen  , the database query is triggered again, and an N+1 query problem occurs.

3. Methods to add associations

var role 
 = 
 = 
 = 
 = 
 = 
 = menus
 = 

if err := (&role).Error; err != nil {
	return err
}

When creating a new user, the user Menus field is the route to be added (queried from the database), and then create it directly. After creation, the Menus field will not be displayed in the database, but role_menu_table will automatically add the association.

By default,UpdatesMethods only update the data of the main table.The association will not be automatically updated,becauseMenusIt is throughmany2manyRelationship maintenance, therefore explicit operations are required to synchronizeMenusandrole_menu_tableThe associated data:

if err := (&role).Association("Menus").Replace(menus); err != nil {
    return err
}

When deleting, delete the association first. Preload is also required when first, otherwise it will fail to clear and cause the final deletion to fail.

//Find the instance and delete itif err := ("Menus").First(&role, id).Error; err != nil {
	return err
}

//Delete the associated Menusif len() > 0 {
	if err := (&role).Association("Menus").Clear(); err != nil {
		return err
	}
}

//Delete the instanceif err := ().Delete(&role).Error; err != nil {
	return err
}

This is the end of this article about golang's project practice to implement dynamic routing. For more related golang dynamic routing content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!