博客系统的核心功能包括文章的crud操作、模板渲染、分页、搜索和评论功能。1. 数据模型设计:创建包含id、title、content、author、created_at、updated_at字段的文章表;2. crud实现:使用insert、select、update、delete语句完成文章的增删改查;3. 模板引擎:通过html/template包加载html模板并渲染文章数据;4. 分页显示:结合limit和offset查询指定页数据,并在模板中展示分页链接;5. 搜索功能:通过like语句实现关键词搜索,并展示匹配结果;6. 评论功能:创建评论表结构,实现评论提交、存储及在文章页面展示评论列表。
Golang开发简易博客系统,核心在于搭建一个能够处理HTTP请求、连接数据库、渲染模板的服务器。文章发布和展示是基本功能,需要设计好数据模型和路由。
首先,我们需要明确博客系统的基本功能:文章的创建、编辑、删除和展示。其次,选择合适的数据库存储文章数据,例如SQLite、MySQL或PostgreSQL。最后,使用Golang的模板引擎渲染页面。
文章表是博客系统的核心,需要存储文章的标题、内容、作者、发布时间等信息。一个典型的文章表结构如下:
立即学习“go语言免费学习笔记(深入)”;
CREATE TABLE articles ( id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR(255) NOT NULL, content TEXT NOT NULL, author VARCHAR(255) NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP );
id 是主键,自增长;title 是文章标题;content 是文章内容;author 是作者;created_at 是创建时间;updated_at 是更新时间。使用Golang的database/sql包可以方便地操作数据库。例如,插入一条新文章:
db, err := sql.Open("sqlite3", "blog.db") if err != nil { log.Fatal(err) } defer db.Close() title := "我的第一篇博客" content := "这是我的第一篇博客内容。" author := "张三" stmt, err := db.Prepare("INSERT INTO articles(title, content, author) VALUES(?, ?, ?)") if err != nil { log.Fatal(err) } defer stmt.Close() _, err = stmt.Exec(title, content, author) if err != nil { log.Fatal(err) } fmt.Println("文章发布成功!")
这里使用了SQLite数据库,实际项目中可以根据需要选择其他数据库。
CRUD(Create, Read, Update, Delete)是数据库操作的基本操作。
rows, err := db.Query("SELECT id, title, content, author, created_at FROM articles") if err != nil { log.Fatal(err) } defer rows.Close() for rows.Next() { var id int var title, content, author string var createdAt time.Time err = rows.Scan(&id, &title, &content, &author, &createdAt) if err != nil { log.Fatal(err) } fmt.Printf("ID: %d, Title: %s, Author: %s, Created At: %s\n", id, title, author, createdAt) } err = rows.Err() if err != nil { log.Fatal(err) }
stmt, err := db.Prepare("UPDATE articles SET title = ? WHERE id = ?") if err != nil { log.Fatal(err) } defer stmt.Close() newTitle := "更新后的标题" articleID := 1 _, err = stmt.Exec(newTitle, articleID) if err != nil { log.Fatal(err) } fmt.Println("文章更新成功!")
stmt, err := db.Prepare("DELETE FROM articles WHERE id = ?") if err != nil { log.Fatal(err) } defer stmt.Close() articleID := 1 _, err = stmt.Exec(articleID) if err != nil { log.Fatal(err) } fmt.Println("文章删除成功!")
Golang的html/template包提供了强大的模板引擎,可以方便地将数据渲染到HTML页面中。首先,创建一个HTML模板文件,例如article.html:
<!DOCTYPE html> <html> <head> <title>{{.Title}}</title> </head> <body> <h1>{{.Title}}</h1> <p>作者:{{.Author}},发布时间:{{.CreatedAt}}</p> <hr /> <div>{{.Content}}</div> </body> </html>
然后,在Golang代码中加载模板并渲染数据:
type Article struct { ID int Title string Content string Author string CreatedAt time.Time } func viewArticleHandler(w http.ResponseWriter, r *http.Request) { articleID := 1 // 假设要查看ID为1的文章 // 从数据库中查询文章 db, err := sql.Open("sqlite3", "blog.db") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer db.Close() row := db.QueryRow("SELECT id, title, content, author, created_at FROM articles WHERE id = ?", articleID) var article Article err = row.Scan(&article.ID, &article.Title, &article.Content, &article.Author, &article.CreatedAt) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // 加载模板 tmpl, err := template.ParseFiles("article.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // 渲染模板 err = tmpl.Execute(w, article) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } }
最后,注册路由并启动服务器:
http.HandleFunc("/article", viewArticleHandler) log.Fatal(http.ListenAndServe(":8080", nil))
这样,访问http://localhost:8080/article就可以看到渲染后的文章页面。
分页显示文章列表可以提高用户体验,避免一次性加载过多数据。
func getTotalArticlesCount(db *sql.DB) (int, error) { var count int err := db.QueryRow("SELECT COUNT(*) FROM articles").Scan(&count) return count, err } func calculateTotalPages(totalArticles, articlesPerPage int) int { return int(math.Ceil(float64(totalArticles) / float64(articlesPerPage))) }
func getArticlesByPage(db *sql.DB, page, articlesPerPage int) ([]Article, error) { offset := (page - 1) * articlesPerPage rows, err := db.Query("SELECT id, title, content, author, created_at FROM articles ORDER BY created_at DESC LIMIT ? OFFSET ?", articlesPerPage, offset) if err != nil { return nil, err } defer rows.Close() var articles []Article for rows.Next() { var article Article err := rows.Scan(&article.ID, &article.Title, &article.Content, &article.Author, &article.CreatedAt) if err != nil { return nil, err } articles = append(articles, article) } return articles, nil }
<div class="pagination"> {{if .HasPrevious}} <a href="/articles?page={{.PreviousPage}}">上一页</a> {{end}} {{range .Pages}} <a href="/articles?page={{.}}">{{.}}</a> {{end}} {{if .HasNext}} <a href="/articles?page={{.NextPage}}">下一页</a> {{end}} </div>
在Golang代码中,需要将分页信息传递给模板:
type PageData struct { Articles []Article CurrentPage int TotalPages int Pages []int HasPrevious bool HasNext bool PreviousPage int NextPage int } func articlesListHandler(w http.ResponseWriter, r *http.Request) { pageStr := r.URL.Query().Get("page") page, err := strconv.Atoi(pageStr) if err != nil || page < 1 { page = 1 } articlesPerPage := 10 db, err := sql.Open("sqlite3", "blog.db") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer db.Close() totalArticles, err := getTotalArticlesCount(db) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } totalPages := calculateTotalPages(totalArticles, articlesPerPage) articles, err := getArticlesByPage(db, page, articlesPerPage) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } pageData := PageData{ Articles: articles, CurrentPage: page, TotalPages: totalPages, HasPrevious: page > 1, HasNext: page < totalPages, PreviousPage: page - 1, NextPage: page + 1, } // 生成页码列表 var pages []int for i := 1; i <= totalPages; i++ { pages = append(pages, i) } pageData.Pages = pages tmpl, err := template.ParseFiles("articles_list.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } err = tmpl.Execute(w, pageData) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } }
实现文章搜索功能,需要允许用户输入关键词,并在数据库中搜索包含该关键词的文章。
<form action="/search" method="GET"> <input type="text" name="keyword" placeholder="输入关键词"> <button type="submit">搜索</button> </form>
func searchArticlesHandler(w http.ResponseWriter, r *http.Request) { keyword := r.URL.Query().Get("keyword") db, err := sql.Open("sqlite3", "blog.db") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer db.Close() // 使用 LIKE 语句进行模糊搜索 query := "%" + keyword + "%" rows, err := db.Query("SELECT id, title, content, author, created_at FROM articles WHERE title LIKE ? OR content LIKE ?", query, query) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer rows.Close() var articles []Article for rows.Next() { var article Article err := rows.Scan(&article.ID, &article.Title, &article.Content, &article.Author, &article.CreatedAt) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } articles = append(articles, article) } // 将搜索结果传递给模板 tmpl, err := template.ParseFiles("search_results.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } err = tmpl.Execute(w, articles) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } }
<!DOCTYPE html> <html> <head> <title>搜索结果</title> </head> <body> <h1>搜索结果</h1> <ul> {{range .}} <li> <a href="/article?id={{.ID}}">{{.Title}}</a> </li> {{end}} </ul> </body> </html>
评论功能可以增加博客的互动性。
CREATE TABLE comments ( id INTEGER PRIMARY KEY AUTOINCREMENT, article_id INTEGER NOT NULL, author VARCHAR(255) NOT NULL, content TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (article_id) REFERENCES articles(id) );
<form action="/comment" method="POST"> <input type="hidden" name="article_id" value="{{.ID}}"> <input type="text" name="author" placeholder="您的名字"> <textarea name="content" placeholder="评论内容"></textarea> <button type="submit">提交评论</button> </form>
func addCommentHandler(w http.ResponseWriter, r *http.Request) { articleIDStr := r.FormValue("article_id") articleID, err := strconv.Atoi(articleIDStr) if err != nil { http.Error(w, "Invalid article ID", http.StatusBadRequest) return } author := r.FormValue("author") content := r.FormValue("content") db, err := sql.Open("sqlite3", "blog.db") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer db.Close() stmt, err := db.Prepare("INSERT INTO comments(article_id, author, content) VALUES(?, ?, ?)") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer stmt.Close() _, err = stmt.Exec(articleID, author, content) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // 重定向回文章页面 http.Redirect(w, r, "/article?id="+articleIDStr, http.StatusSeeOther) }
func getCommentsByArticleID(db *sql.DB, articleID int) ([]Comment, error) { rows, err := db.Query("SELECT id, author, content, created_at FROM comments WHERE article_id = ?", articleID) if err != nil { return nil, err } defer rows.Close() var comments []Comment for rows.Next() { var comment Comment err := rows.Scan(&comment.ID, &comment.Author, &comment.Content, &comment.CreatedAt) if err != nil { return nil, err } comments = append(comments, comment) } return comments, nil }
在文章模板中显示评论:
<h2>评论列表</h2> <ul> {{range .Comments}} <li> <strong>{{.Author}}</strong>:{{.Content}} <small>({{ .CreatedAt }})</small> </li> {{end}} </ul>
这些步骤可以帮助你用Golang构建一个简易的博客系统,实现文章发布与展示功能。
以上就是Golang如何开发一个简易的博客系统 实现文章发布与展示功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号