惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threatpost
博客园 - 叶小钗
T
The Blog of Author Tim Ferriss
Recent Announcements
Recent Announcements
D
DataBreaches.Net
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
Netflix TechBlog - Medium
Microsoft Azure Blog
Microsoft Azure Blog
Microsoft Security Blog
Microsoft Security Blog
B
Blog
U
Unit 42
有赞技术团队
有赞技术团队
博客园 - 聂微东
GbyAI
GbyAI
宝玉的分享
宝玉的分享
F
Full Disclosure
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
MyScale Blog
MyScale Blog
Jina AI
Jina AI
Martin Fowler
Martin Fowler
IT之家
IT之家
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Docker
P
Proofpoint News Feed
A
About on SuperTechFans
I
InfoQ
博客园 - 【当耐特】
C
Check Point Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy & Cybersecurity Law Blog
T
Threat Research - Cisco Blogs
Y
Y Combinator Blog
Project Zero
Project Zero
WordPress大学
WordPress大学
小众软件
小众软件
AWS News Blog
AWS News Blog
博客园 - 司徒正美
T
The Exploit Database - CXSecurity.com
L
LINUX DO - 热门话题
I
Intezer
Engineering at Meta
Engineering at Meta
C
CXSECURITY Database RSS Feed - CXSecurity.com
J
Java Code Geeks
T
Tenable Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Last Week in AI
Last Week in AI
C
CERT Recently Published Vulnerability Notes

文章列表 on polarisxu

通过一个例子让你彻底掌握 Go 工作区模式 这道题正确率竟然只有 22% Go 开源项目推荐:一个简单的 Go 练手项目 go test 如何禁用缓存? Go1.18 快讯:constraints 包被移除标准库 跟着 Go 作者学泛型 「2022 版」轻松搞定 Go 开发环境 鹅厂小哥用行动反对加班:程序员加班能被终结吗? Go 为什么选择 Gopher 作为吉祥物? 本地如何配置多个 GitHub/Gitee 账号? 为 Java 开发者准备的 Go 教程 02:Java 有而 Go 无 GitHub 发现了 studygolang 项目依赖的漏洞 Typora 宣布收费后,这款开源 Markdown 编辑器火了 为 Java 开发者准备的 Go 教程 01:漫游了 我的 2021 年终总结 泛型版 singleflight:Go 中如何防止缓存击穿? 2021 年你写了多少代码?这个 Go 工具帮你统计 Go1.18 新特性:TryLock Go 泛型入门教程 程序员瑞士军刀:各种结构的转换工具 终于有 Go 版的 Elasticsearch 了 Go泛型系列:maps 包讲解 Go 1.18 中的 any 是什么? Go1.18 快讯:新的 IP 包 Go编程模式:详解函数式选项模式 Go泛型系列:slices 包讲解 Nginx 竟然也有 playground — Go 语言构建的 Go泛型系列:Go1.18 类型约束那些事 Go1.18 快讯:Module 工作区模式 Go1.18 快讯:新增的 Cut 函数太方便了 Go1.18 快讯:废弃了这个 API Go1.18 快讯:新增字符串 Clone API Go:如何获得项目根目录? Go 如何获取和设置环境变量 重磅变动:更快找到微信公众号里的Go文章 Go 这样设置版本号:我们的项目也可以 假期结束,推荐 2 本 manning 出的 Go 图书 Go Fiber 框架系列教程 04:测试应用 Go Fiber 框架系列教程 03:中间件 Go泛型系列:提前掌握Go泛型的基本使用 推荐一个 Go GUI 实战项目 Go Fiber 框架系列教程 02:详解相关 API 的使用 Go Fiber 框架系列教程 01: 和 Express 对比学习 Go Module:私有不合规库怎么解决引用问题 Go1.17 新特性:go get 变了 Go1.17 新特性:testing 包的相关变化 StackOverflow 上关于 Go select 死锁的问题 新书推荐:用 Gin 框架构建分布式应用 Go 官网要变天。。。 Gin 这是要成为 Go 官方框架? 扬眉吐气:刚刚,Go 已经默认支持泛型了 Go 1.17 新特性:Module 有哪些变化? Go 第三方库推荐:类型转换如此简单 担心密码提交到 GitHub?建议使用这个 Go 开源工具 Go 的时间格式化为什么是 2006-01-02 15:04:05? GitHub 为 Go 社区带来安全支持 Go开源项目推荐:500行代码确认请求时间花在哪 一道关于 len 函数的诡异 Go 面试题解析 厉害了我的 Go:推荐系统都有开源实现 Go1.17 新特性:新版构建约束 这个工具真好:看看你的Go项目依赖有无漏洞 网友很强大,发现了Go并发下载的Bug Rust 劝退系列 09:函数 Go项目实战:一步步构建一个并发文件下载器 这本 Go 新书挺期待的:100 个常见错误 Go 启用新的官方问答社区 这是要干嘛?!微软招 Go 编译器全职开发人员 Go1.17 快报之标准库越来越注重易用性 Go1.17 新特性之切片变数组 回顾 Go 官网的演变史 站长8年前的Go代码竟然进入大厂的项目里了 Go图书翻译:一个好消息,一个坏消息 不怕烂尾!决定组织翻译这本 Go 图书 Rust 劝退系列 08:模式匹配 一本花了2.5年写成的Go免费在线图书 被黑惨了:一句话,说明自己会 Go,咋整? Go1.16 中的新函数 signal.NotifyContext 怎么用? Go 1.17 新特性提前学之测试执行随机化 Rust 劝退系列 07:流程控制 官方的 Go 多版本管理:使用和原理 Rust新书:给你一个劝退的理由 周刊题解:常量表达式这个规则应该了解下 盘点那些使用 Go 语言的国外公司 编写了50万行Go代码是一种什么体验 Rust 劝退系列 06:常量 Uber 使用 Go 的规模这么大?!都自己定制的 Go 编译器了 Go Team Leader — rsc 大神新开源了一个库,增强模板功能 再一次看到了 Go 的节制:int128 类型要不要支持? Rust 劝退系列 05:复合数据类型 「卷」有理论依据:海勒姆定律—Go又是怎么卷的 Go 真的也可以进行 GUI 开发:还有这样的图书呢 Rust 劝退系列 04:基本数据类型 我的 Go 语言书单 Rust 劝退系列 03:变量 我又来推荐免费 Go 新书了:一本用 Go 讲架构的书 注释竟然还有特殊用途?一文解惑 //go:linkname 指令 这个功能,公众号、微信群会不会被玩坏? 一道 Go 闭包题,面试官说原来自己答错了:面别人也涨知识 Rust 劝退系列 02:第一个 Rust 程序 Rust 劝退系列 01:打造开发环境
基于 Go1.16 实现静态文件的 HTTP Cache
2021-01-10 · via 文章列表 on polarisxu

大家好,我是站长 polarisxu。

之前写过一篇文章:《提前试用将在 Go1.16 中发布的内嵌静态资源功能》 ,如果之前没阅读,建议继续看本文前先阅读下该文。

现在 Go 1.16 Beta 已经发布,离正式版发布不远了,在 GitHub 发现了一个库,它实现了 io/fs.FS 接口,它能够计算文件的 SHA256 哈希值并附加到文件名中以允许进行 HTTP Cache:即控制静态文件的版本。本文对其进行介绍并顺带讲解一些涉及到的其他内容。

温馨提示:本文内容基于 Go 1.16 Beta,之前版本不支持!

01 hashfs 包

包地址:https://github.com/benbjohnson/hashfs,有效代码函数不到 200。

对于给定的一个文件,比如 scripts/main.js,hashfs.FS 文件系统处理后会生成一个带 hash 的文件,类似 scripts/main-b633a..d628.js(中间有省略),客户端请求该文件时,可以选择让客户端缓存。hash 算法使用的是 SHA256。当文件内容发生变化时,hash 值也会变。

该包默认提供对 net/http 的兼容。通过例子看看具体怎么使用。

02 基于 net/http 的使用

创建一个目录,使用 module:

$ mkdir ~/embed
$ cd ~/embed
$ go mod init gtihub.com/polaris1119/embed

为了基于同一个项目演示不同使用方式,创建如下目录结构:

├── cmd
│   ├── std
│   │   └── main.go
├── embed.go
├── go.mod
├── go.sum
├── static
│   └── main.js	// 主要处理该文件的嵌入、hash
├── template
│   └── index.html

其中 embed.go 的作用在本文开头文章提到过,内容如下:

package embed

import (
	"embed"

	"github.com/benbjohnson/hashfs"
)

//go:embed static
var embedFS embed.FS

// 带 hash 功能的 fs.FS
var Fsys = hashfs.NewFS(embedFS)

再说一句,因为 //go:embed 只能相对当前源文件所在目录,所以单独创建这个文件以便和 static 在同一级目录。

index.html 和 main.js 的内容很简单。

index.html:

<html>
  <head>
    <title>测试 Embed Hash</title>
    <script src="/assets/{{.mainjs}}"></script>
  </head>
  <body>
    <h1>测试 Embed Hash</h1>
    <hr>
    <div>
      以下内容来自 JS:
    </div>
    <p id="content" style="color: red;"></p>
  </body>
</html>

该模板中有一个变量:mainjs。

main.js:

window.onload = function() {
    document.querySelector('#content').innerHTML = "我是 JS 内容";
}

如果一切正常,看到的页面如下:

在 cmd/std/main.go 中写上如下代码:

package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"

	"github.com/benbjohnson/hashfs"
	"github.com/polaris1119/embed"
)

func main() {
	http.Handle("/assets/", http.StripPrefix("/assets/", hashfs.FileServer(embed.Fsys)))

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		tpl, err := template.New("index.html").ParseFiles("template/index.html")
		if err != nil {
			fmt.Fprint(w, err.Error())
			return
		}

		err = tpl.Execute(w, map[string]interface{}{
			"mainjs": embed.Fsys.HashName("static/main.js"),
		})
		if err != nil {
			fmt.Fprint(w, err.Error())
			return
		}
	})

	log.Fatal(http.ListenAndServe(":8080", nil))
}
  • 特意为静态资源加上 /assets/ 前缀,后文解释;
  • hashfs.FileServer(embed.Fsys)) 是 hashfs 包对 net/http 的支持,即 hashfs.FileServer 是一个 http.Handler;
  • embed.Fsys.HashName("static/main.js") 将文件生成为带 hash 的;

执行 go run ./cmd/std/main.go,打开浏览器访问:http://localhost:8080 即可看到上面截图的页面,审查元素可以看到如下信息,缓存一年。(见代码:https://github.com/benbjohnson/hashfs/blob/main/hashfs.go#L200

当你再次刷新浏览器,看到 js 文件直接从缓存获取的。

当 main.js 的内容发生变化,main-xxx.js 中的 hash 部分也会变化,你可以自行试验。(注意,因为资源内嵌了,修改了 js 的内容,需要重新 go run)。

03 关于服务静态文件

这块有必要单独拿出来说下,因为比较容易搞错。比如上面的一行代码改为这样:

http.Handle("/assets", http.StripPrefix("/assets", hashfs.FileServer(embed.Fsys)))

再次运行结果就不对(没有 “我是 JS 内容”)。(注意禁用浏览器缓存,否则看不到效果)

如果是 Echo 框架,则可以:

Gin 框架,也可以:

router.Static("/assets", ".")

关于其中的细节,大家有兴趣可以查阅相关源码。这里只要记住,服务目录,末尾加上 /,(目录嘛,应该有 /),即:

http.Handle("/assets/", ...)

04 基于 Echo 的使用

在 cmd 目录下创建 echo/main.go 文件:

package main

import (
	"bytes"
	"fmt"
	"io"
	"mime"
	"net/http"
	"net/url"
	"os"
	"path"
	"strconv"
	"text/template"

	"github.com/benbjohnson/hashfs"
	"github.com/labstack/echo/v4"
	"github.com/polaris1119/embed"
)

func main() {
	e := echo.New()

	e.GET("/assets/*", func(ctx echo.Context) error {
		filename, err := url.PathUnescape(ctx.Param("*"))
		if err != nil {
			return err
		}

		isHashed := false
		if base, hash := hashfs.ParseName(filename); hash != "" {
			if embed.Fsys.HashName(base) == filename {
				filename = base
				isHashed = true
			}
		}

		f, err := embed.Fsys.Open(filename)
		if os.IsNotExist(err) {
			return echo.ErrNotFound
		} else if err != nil {
			return echo.ErrInternalServerError
		}
		defer f.Close()

		// Fetch file info. Disallow directories from being displayed.
		fi, err := f.Stat()
		if err != nil {
			return echo.ErrInternalServerError
		} else if fi.IsDir() {
			return echo.ErrForbidden
		}

		contentType := "text/plain"
		// Determine content type based on file extension.
		if ext := path.Ext(filename); ext != "" {
			contentType = mime.TypeByExtension(ext)
		}

		// Cache the file aggressively if the file contains a hash.
		if isHashed {
			ctx.Response().Header().Set("Cache-Control", `public, max-age=31536000`)
		}

		// Set content length.
		ctx.Response().Header().Set("Content-Length", strconv.FormatInt(fi.Size(), 10))

		// Flush header and write content.
		buf := new(bytes.Buffer)
		if ctx.Request().Method != "HEAD" {
			io.Copy(buf, f)
		}
		return ctx.Blob(http.StatusOK, contentType, buf.Bytes())
	})

	e.GET("/", func(ctx echo.Context) error {
		tpl, err := template.New("index.html").ParseFiles("template/index.html")
		if err != nil {
			return err
		}

		var buf = new(bytes.Buffer)
		err = tpl.Execute(buf, map[string]interface{}{
			"mainjs": embed.Fsys.HashName("static/main.js"),
		})
		if err != nil {
			return err
		}
		return ctx.HTML(http.StatusOK, buf.String())
	})

	e.Logger.Fatal(e.Start(":8080"))
}

简单解释下服务静态文件的实现原理:

  • 获取请求的路径(* 部分);
  • 通过 hashfs.ParseName 解析出文件的 base 和 hash 两部分;
  • 使用 fs.FS 打开文件,判断文件类型、大小,并将内容返回给客户端,如果有缓存,设置 HTTP Cache;

运行 go run ./cmd/echo/main.go,不出意外和 net/http 版本一样的效果。

05 基于 Gin 的使用

其实知道了如何基于 Echo 框架使用,其他框架参照着实现即可。因为 Gin 框架用户多,因此也实现下。

在 cmd 目录下创建文件:gin/main.go

package main

import (
	"bytes"
	"io"
	"mime"
	"net/http"
	"net/url"
	"os"
	"path"
	"strconv"
	"strings"

	"github.com/benbjohnson/hashfs"
	"github.com/gin-gonic/gin"
	"github.com/polaris1119/embed"
)

func main() {
	r := gin.Default()

	r.GET("/assets/*filepath", func(ctx *gin.Context) {
		filename, err := url.PathUnescape(ctx.Param("filepath"))
		if err != nil {
			ctx.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		filename = strings.TrimPrefix(filename, "/")

		isHashed := false
		if base, hash := hashfs.ParseName(filename); hash != "" {
			if embed.Fsys.HashName(base) == filename {
				filename = base
				isHashed = true
			}
		}

		f, err := embed.Fsys.Open(filename)
		if os.IsNotExist(err) {
			ctx.AbortWithError(http.StatusNotFound, err)
			return
		} else if err != nil {
			ctx.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		defer f.Close()

		// Fetch file info. Disallow directories from being displayed.
		fi, err := f.Stat()
		if err != nil {
			ctx.AbortWithError(http.StatusInternalServerError, err)
			return
		} else if fi.IsDir() {
			ctx.AbortWithError(http.StatusForbidden, err)
			return
		}

		contentType := "text/plain"
		// Determine content type based on file extension.
		if ext := path.Ext(filename); ext != "" {
			contentType = mime.TypeByExtension(ext)
		}

		// Cache the file aggressively if the file contains a hash.
		if isHashed {
			ctx.Writer.Header().Set("Cache-Control", `public, max-age=31536000`)
		}

		// Set content length.
		ctx.Writer.Header().Set("Content-Length", strconv.FormatInt(fi.Size(), 10))

		// Flush header and write content.
		buf := new(bytes.Buffer)
		if ctx.Request.Method != "HEAD" {
			io.Copy(buf, f)
		}
		ctx.Data(http.StatusOK, contentType, buf.Bytes())
	})

	r.LoadHTMLGlob("template/*")
	r.GET("/", func(ctx *gin.Context) {
		ctx.HTML(http.StatusOK, "index.html", gin.H{
			"mainjs": embed.Fsys.HashName("static/main.js"),
		})
	})
	r.Run(":8080")
}

服务静态文件的内容和 Echo 框架基本一样,除了各自框架特有的。

因为 Gin 框架提供了 LoadHTMLGlob,首页路由的处理函数代码很简单。

运行 go run ./cmd/gin/main.go,不出意外和 net/http 版本一样的效果。

06 总结

举一反三,在学习过程中可以让你更好的掌握某个知识点。

之前有读者问到 module 如何使用 vendor(没网情况下使用)。今天试验这个就是用了 vendor。其实它的使用很简单,在项目下执行:go mod vendor 即可。不过需要注意的是,加入了新的依赖,就应该执行一次 go mod vendor。

今天介绍的这个库在这个时代用到的可能性不高,不过也有可能会用得到。更重要的是希望这篇文章可以作为一个小项目实践下。希望你能从头自己编码实现。

另外还留了一个问题给你:index.html 文件没有内嵌,请你自己完成。(提示:html/template 增加了对 io/fs.Fs 的支持)

本项目完整代码:https://github.com/polaris1119/embed