富在术数不在劳身,利在局势不在力耕
一直想写一个完全自己实现的Go博客站,但奈何一直使用python写django后端django写后端虽然有现成的教程,但总是感觉有点老旧,直到闲暇时间去看FastAPI框架,发现其中的有些思想和gin相似,推荐的orm框架也和gorm类似,又凑巧看到了一个比较简洁的博客,结合现在开始写笔记,于是就想做一个在线的笔记本,也就是个人的博客,于是就有了这篇笔记,这篇笔记是在django中记录,并将迁移到go写成多的博客中
网络请求使用的是gin框架,gin框架基于go的het/http,性能很不错。
首先是让gin能响应网络请求。添加路由,为了后续的项目好维护,将路由和视图分开写(本人一直使用django开发)在项目根目录下新建路由文件router.go
package main
import (
"md_blog/view"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
)
func RouterMapper(router *gin.Engine) {
store := cookie.NewStore([]byte("secret"))
router.Use(sessions.Sessions("mysession", store))
router.GET("/", view.Index)
router.GET("/page/:page", view.Index)
router.GET("/login", view.Login)
router.POST("/login", view.LoginForm)
router.GET("/logout", view.Logout)
router.GET("/md", view.MD)
router.GET("/md/:id", view.MD)
router.POST("/addcategory", view.AddCategory)
router.POST("/editor/:id", view.PostMDEditor)
router.GET("/editor/:id", view.MDEditor)
router.POST("/editor", view.PostMDEditor)
router.GET("/editor", view.MDEditor)
router.NoRoute(view.NotFound)
}
这是暂时全部的路由,当然项目现在还在持续的开发中,但是有朝一日总会趋于完善
gin官方默认给了很多的中间件可用项目地址
在视图层进行相关逻辑的处理,新建view/md_view.go
,视图的代码未完全放出
package view
import (
"fmt"
"net/http"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
//简单封装了HTML方法
func success(ctx *gin.Context, template string, obj any) {
ctx.HTML(http.StatusOK, template, obj)
}
//临时重定向
func reidrect(ctx *gin.Context, path string) {
ctx.Redirect(http.StatusTemporaryRedirect, path)
}
//404
func notfound(ctx *gin.Context) {
ctx.HTML(http.StatusNotFound, "notfound.tmpl", nil)
}
func Index(ctx *gin.Context) {
session := sessions.Default(ctx)
// if session.Get("hello") != "world" {
// session.Set("hello", "world")
// session.Save()
// } else {
session.Set("user", "user")
session.Save()
// }
// ctx.JSON(200, gin.H{"hello": session.Get("hello")})
success(ctx, "index.html", gin.H{
"path": "/",
})
}
func MD(ctx *gin.Context) {
session := sessions.Default(ctx)
// 新增页面,未登录就跳转到登录页面
if session.Get("user") != "user" {
fmt.Println(session.Get("user"))
reidrect(ctx, "/login")
return
}
success(ctx, "md.html", gin.H{
"user": "user",
"path": "/md",
})
}
数据结构
package model
import (
"time"
"gorm.io/gorm"
)
type Mds struct {
gorm.Model
// 标题
Title string
// 内容
Content string
// 用户
User User
UserID *uint
// 发布时间
PubTime *time.Time
// 分类
CategoriesID *uint
Categories Categories
// 标签,多对多
Tags []Tag `gorm:"many2many:mds_tags;"`
}
使用压测工具简单的测了一下,新能确实是比django好一些,当然了,如果后端再进行一些优化,性能可能会更好。
文章分类