search
HomeBackend DevelopmentGolangGolang implements multi-level comments

With the rise of social media and content platforms, multi-level comment systems have become an important way for various platforms to interact with users and communities. It is relatively simple to implement a multi-level comment system on the front end, but it is relatively complicated to implement on the back end. This article will introduce how to use golang to implement multi-level comments.

Implementation ideas

Multi-level comments are actually a display of a tree structure, and each comment can be used as a node. Multi-level review systems can be implemented using tree and binary trees, the basic data structures of tree structures. In this article, we choose to use a tree-structured binary tree for implementation.

The node of the binary tree consists of two left and right child nodes. The left node is the first child node of the current node, and the right node is the second child node of the current node. Therefore, every time we add a comment, we only need to pay attention to the parent node of the current comment and its left and right child nodes.

Database Design

In order to implement a multi-level comment system, the parent-child relationship of each comment needs to be stored in the database. In general, we can use two ways to store the tree structure:

  1. Use multi-table association
  2. Use self-referential relationships in a single table

In this article, we choose to use the second method, which is to use self-referential relationships in a single table.

The structure of the comment table (comment) is as follows:

CREATE TABLE `comment` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `parent_id` int(11) DEFAULT NULL COMMENT '父级评论id',
  `content` varchar(255) DEFAULT NULL COMMENT '评论内容',
  `created_at` datetime DEFAULT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`),
  KEY `parent_id` (`parent_id`),
  CONSTRAINT `comment_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `comment` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='评论表'

In the above table structure, parent_id represents the parent node id of the current comment, if the current comment is a first-level comment , then parent_id is null. id is the id of the current comment, content is the comment content, and created_at is the creation time.

Code implementation

First, you need to use the database/sql and mysql drivers in golang to link to the database:

dsn := "root:123456@tcp(127.0.0.1:3306)/test"
db, err := sql.Open("mysql", dsn)
if err != nil {
   fmt.Printf("mysql connect error %s", err.Error())
   return
}

Insert comment

When inserting a comment, you need to determine whether the current comment is processed as a parent node or a child node.

If the current comment is used as a parent node, it is inserted directly into the database. If the current comment is a child node, the right node of the parent node needs to be updated.

// 添加评论
func AddComment(comment Comment) error {
   if comment.ParentID == 0 {
       _, err := db.Exec("INSERT INTO comment(parent_id, content, created_at) VALUES(?, ?, ?)", nil, comment.Content, comment.CreatedAt)
       if err != nil {
           return err
       }
   } else {
       var rightNode *int
       err := db.QueryRow("SELECT right_node FROM comment WHERE id = ?", comment.ParentID).Scan(&rightNode)
       if err != nil {
           return err
       }
       tx, err := db.Begin()
       if err != nil {
           return err
       }
       // 更新右节点
       _, err = tx.Exec("UPDATE comment SET right_node = right_node + 2 WHERE right_node > ?", rightNode)
       if err != nil {
           tx.Rollback()
           return err
       }
       _, err = tx.Exec("UPDATE comment SET left_node = left_node + 2 WHERE left_node > ?", rightNode)
       if err != nil {
           tx.Rollback()
           return err
       }
       _, err = tx.Exec("INSERT INTO comment(parent_id, left_node, right_node, content, created_at) VALUES(?, ?, ?, ?, ?)", comment.ParentID, rightNode, rightNode+1, comment.Content, comment.CreatedAt)
       if err != nil {
           tx.Rollback()
           return err
       }
       tx.Commit()
   }
   return nil
}

Query comments

When querying comments, you need to sort the nodes in left and right order to obtain a tree-structured comment list. When querying comments, since the left and right nodes need to be used for sorting, the left and right node columns need to be added to the query conditions. In addition, you also need to use a level field to indicate which level of node the current node is to facilitate front-end display.

type Comment struct {
   ID        int    `json:"id"`
   ParentID  int    `json:"parent_id"`
   Content   string `json:"content"`
   LeftNode  int    `json:"left_node"`
   RightNode int    `json:"right_node"`
   Level     int    `json:"level"`
   CreatedAt string `json:"created_at"`
}

// 获取评论列表
func GetComments() ([]Comment, error) {
   rows, err := db.Query("SELECT id, parent_id, content, created_at, left_node, right_node, (COUNT (parent.id) -1) AS level FROM comment AS node, comment AS parent WHERE node.left_node BETWEEN parent.left_node AND parent.right_node GROUP BY node.id ORDER BY left_node")
   if err != nil {
       return nil, err
   }
   defer rows.Close()

   var comments []Comment
   for rows.Next() {
       var comment Comment
       err := rows.Scan(&comment.ID, &comment.ParentID, &comment.Content, &comment.CreatedAt, &comment.LeftNode, &comment.RightNode, &comment.Level)
       if err != nil {
           return nil, err
       }
       comments = append(comments, comment)
   }
   return comments, nil
}

Delete comments

When deleting a comment, you need to determine whether the current comment is a parent node or a child node. If it is a parent node, you need to delete the entire subtree.

// 删除评论
func DeleteComment(id int) error {
   tx, err := db.Begin()
   if err != nil {
       return err
   }
   var leftNode int
   var rightNode int
   err = tx.QueryRow("SELECT left_node, right_node FROM comment WHERE id = ?", id).Scan(&leftNode, &rightNode)
   if err != nil {
       tx.Rollback()
       return err
   }
   if leftNode == 1 && rightNode > 1 {
       // 删除子树
       _, err = tx.Exec("DELETE FROM comment WHERE left_node >= ? AND right_node <= ?;", leftNode, rightNode)
       if err != nil {
           tx.Rollback()
           return err
       }
       err = tx.Commit()
       if err != nil {
           tx.Rollback()
           return err
       }
   } else {
       // 删除单个节点
       _, err = tx.Exec("DELETE FROM comment WHERE id = ?", id)
       if err != nil {
           tx.Rollback()
           return err
       }
       err = tx.Commit()
       if err != nil {
           tx.Rollback()
           return err
       }
   }
   return nil
}

Conclusion

Through the above code implementation, we can quickly build a fully functional multi-level comment system. Of course, this is only a basic implementation method. In actual scenarios, corresponding optimization and expansion need to be made according to specific needs.

The above is the detailed content of Golang implements multi-level comments. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you use the "strings" package to manipulate strings in Go?How do you use the "strings" package to manipulate strings in Go?Apr 30, 2025 pm 02:34 PM

The article discusses using Go's "strings" package for string manipulation, detailing common functions and best practices to enhance efficiency and handle Unicode effectively.

How do you use the "crypto" package to perform cryptographic operations in Go?How do you use the "crypto" package to perform cryptographic operations in Go?Apr 30, 2025 pm 02:33 PM

The article details using Go's "crypto" package for cryptographic operations, discussing key generation, management, and best practices for secure implementation.Character count: 159

How do you use the "time" package to handle dates and times in Go?How do you use the "time" package to handle dates and times in Go?Apr 30, 2025 pm 02:32 PM

The article details the use of Go's "time" package for handling dates, times, and time zones, including getting current time, creating specific times, parsing strings, and measuring elapsed time.

How do you use the "reflect" package to inspect the type and value of a variable in Go?How do you use the "reflect" package to inspect the type and value of a variable in Go?Apr 30, 2025 pm 02:29 PM

Article discusses using Go's "reflect" package for variable inspection and modification, highlighting methods and performance considerations.

How do you use the "sync/atomic" package to perform atomic operations in Go?How do you use the "sync/atomic" package to perform atomic operations in Go?Apr 30, 2025 pm 02:26 PM

The article discusses using Go's "sync/atomic" package for atomic operations in concurrent programming, detailing its benefits like preventing race conditions and improving performance.

What is the syntax for creating and using a type conversion in Go?What is the syntax for creating and using a type conversion in Go?Apr 30, 2025 pm 02:25 PM

The article discusses type conversions in Go, including syntax, safe conversion practices, common pitfalls, and learning resources. It emphasizes explicit type conversion and error handling.[159 characters]

What is the syntax for creating and using a type assertion in Go?What is the syntax for creating and using a type assertion in Go?Apr 30, 2025 pm 02:24 PM

The article discusses type assertions in Go, focusing on syntax, potential errors like panics and incorrect types, safe handling methods, and performance implications.

How do you use the "select" statement in Go?How do you use the "select" statement in Go?Apr 30, 2025 pm 02:23 PM

The article explains the use of the "select" statement in Go for handling multiple channel operations, its differences from the "switch" statement, and common use cases like handling multiple channels, implementing timeouts, non-b

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software