1 Star 0 Fork 0

李小程/blog-lib

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
common.go 2.44 KB
一键复制 编辑 原始数据 按行查看 历史
李小程 提交于 2025-07-19 11:24 +08:00 . fix
package common
import (
"html/template"
"net/http"
"regexp"
"strings"
"gitee.com/xchengli/blog-lib/components"
"gitee.com/xchengli/blog-lib/defines"
"gitee.com/xchengli/blog-lib/zlog"
)
// CommonAction 通用请求处理逻辑
// 记录请求日志,用于统计和分析
func CommonAction(r *http.Request, w http.ResponseWriter) {
go func() {
ctx := components.NewContext()
zlog.Info(ctx, "Request logged", "method", r.Method, "path", r.URL.Path)
}()
}
// SendResult 发送JSON格式的响应结果
// status: 状态码,message: 消息,data: 数据
func SendResult(w http.ResponseWriter, status int, message string, data interface{}) (err error) {
var d = defines.Return{Error: status, Message: message, Data: data}
err = d.ResponseJson(w)
return
}
// RedirectPage 显示跳转页面
// title: 页面标题,message: 提示消息,toUrl: 跳转地址,httpCode: HTTP状态码,waitSecond: 等待秒数
func RedirectPage(w http.ResponseWriter, title, message, toUrl string, httpCode, waitSecond int) {
t, err := template.New("redirect.html").Funcs(components.TemplateFuncs).ParseFiles("templates/redirect.html", "templates/pub_inc.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
param := struct {
Title template.HTML
Message template.HTML
ToUrl template.HTML
HttpCode int
WaitSecond int
}{
Title: template.HTML(title),
Message: template.HTML(message),
ToUrl: template.HTML(toUrl),
HttpCode: httpCode,
WaitSecond: waitSecond,
}
//直接301临时跳转
if waitSecond == 0 {
w.Header().Set("Location", toUrl)
w.WriteHeader(301)
return
}
w.WriteHeader(httpCode) //必须要在Execute之前执行
t.Execute(w, param)
}
// TrimHtml 去除HTML标签,提取纯文本内容
// src: 包含HTML的字符串
func TrimHtml(src string) string {
//将HTML标签全转换成小写
re, _ := regexp.Compile(`\<[\S\s]+?\>`)
src = re.ReplaceAllStringFunc(src, strings.ToLower)
//去除STYLE
re, _ = regexp.Compile(`\<style[\S\s]+?\</style\>`)
src = re.ReplaceAllString(src, "")
//去除SCRIPT
re, _ = regexp.Compile(`\<script[\S\s]+?\</script\>`)
src = re.ReplaceAllString(src, "")
//去除所有尖括号内的HTML代码,并换成换行符
re, _ = regexp.Compile(`\<[\S\s]+?\>`)
src = re.ReplaceAllString(src, "\n")
//去除连续的换行符
re, _ = regexp.Compile(`\s{2,}`)
src = re.ReplaceAllString(src, "\n")
return strings.TrimSpace(src)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/xchengli/blog-lib.git
git@gitee.com:xchengli/blog-lib.git
xchengli
blog-lib
blog-lib
7bad096cf672

搜索帮助