实现性能
- 减少动态页模版
- 减少分页性能
- 解决图片防盗链
本节残缺代码:
https://github.com/golangtips...
减少动态页模版
基于开源 HTML 博客模板 https://github.com/golangtips/django-blog-tutorial-templates,二次批改
main.go 中,减少动态申请解决
r := mux.NewRouter()// 动态文件r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
将模版中 css/js/img 目录,复制 static 目录下
├── static│ ├── css│ │ ├── bootstrap.min.css│ │ ├── custom.css│ │ ├── highlights│ │ │ ├── autumn.css│ │ │ ├── borland.css│ │ │ ├── bw.css│ │ │ ├── colorful.css│ │ │ ├── default.css│ │ │ ├── emacs.css│ │ │ ├── friendly.css│ │ │ ├── fruity.css│ │ │ ├── github.css│ │ │ ├── manni.css│ │ │ ├── monokai.css│ │ │ ├── murphy.css│ │ │ ├── native.css│ │ │ ├── pastie.css│ │ │ ├── perldoc.css│ │ │ ├── tango.css│ │ │ ├── trac.css│ │ │ ├── vim.css│ │ │ ├── vs.css│ │ │ └── zenburn.css│ │ └── pace.css│ ├── img│ │ └── me.jpg│ └── js│ ├── bootstrap.min.js│ ├── jquery-2.1.3.min.js│ ├── modernizr.custom.js│ ├── pace.min.js│ └── script.js
图片防盗链
语雀对图片地址,做了防盗链;在集体域名下,无奈间接拜访
https://cdn.nlark.com/yuque/0/2022/png/1293580/1664030164721-6814a656-7cc3-4a8f-94f5-4b091cc7fc0d.png
解决办法
通过反向代理,解决跨域图片加载
handler/post.go 增加
// CDNProxy 反向代理,解决跨域图片加载问题func CDNProxy(w http.ResponseWriter, r *http.Request) { remote, err := url.Parse("https://cdn.nlark.com") if err != nil { return } proxy := httputil.NewSingleHostReverseProxy(remote) d := proxy.Director proxy.Director = func(r *http.Request) { r.Header.Set("Referer", "") r.Host = remote.Host d(r) } proxy.ServeHTTP(w, r)}// PostDetail 文章详情页func PostDetail(s service.IYuQue) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // 文章内容 content := detail.Data.BodyHtml // 替换html中的cdn链接进行反向代理 content = strings.Replace(content, "https://cdn.nlark.com/", "/", -1) // 模块变量 post := Post{ Title: detail.Data.Title, Content: template.HTML(content), CreatedAt: detail.Data.CreatedAt, } // 省略... }}
cmd/main.go 增加
// 反向代理,解决跨域图片加载问题r.PathPrefix("/yuque/").HandlerFunc(handler.CDNProxy)
减少分页性能
HomePage 处理器,减少分页解决
// HomePage 首页func HomePage(s service.IYuQue) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // 省略.... // 获取文章总数 allDocs, _ := s.GetRepoDocList(r.Context(), nil) total := len(allDocs.Data) // 分页解决 p := util.NewPagination(total, pageSizeInt, pageInt, 10) p.Paginate() t.Execute(w, map[string]interface{}{ "posts": posts, "paginator": p, }) }}
更新 home.html 中 pagination
<div class="pagination"> <ul> {{if .paginator.HasPrev}} <li><a href="?page={{.paginator.FirstPage}}">{{.paginator.FirstPage}}</a></li> ... {{end}} {{$currentPage := .paginator.CurrentPage}} {{range $i := .paginator.Pages}} {{if eq $i $currentPage}} <li class="current"><a href="?page={{$i}}">{{ $i }}</a></li> {{else}} <li><a href="?page={{$i}}">{{ $i }}</a></li> {{end}} {{end}} {{if .paginator.HasNext}} ... <li><a href="?page={{.paginator.TotalPages}}">{{.paginator.TotalPages}}</a></li> {{end}} </ul> </div>