go - 与官方 Docker 镜像相比,Go Mime 包(1.14)在本地表现不同
问题描述
我已经将我的本地 Go 版本从 升级1.13
到1.14
,然后我通过重新初始化使用go mod
.
本地:
$ go version
go version go1.14 linux/amd64
go.mod
我的项目:
module example-project
go 1.14
mime
Go 1.14中的包中有一个更新,将.js
文件的默认类型从 更改application/javascript
为text/javascript
.
我有一个应用程序,它提供一个包含 JavaScript 文件的文件夹,例如:
func main() {
http.HandleFunc("/static/", StaticHandler)
http.ListenAndServe(":3000", nil)
}
func StaticHandler(w http.ResponseWriter, r *http.Request) {
fs := http.StripPrefix("/static", http.FileServer(http.Dir("public/")))
fs.ServeHTTP(w, r)
}
我更新了一个测试用例以反映 Go 1.14 中的 mime 更改:
func TestStaticHandlerServeJS(t *testing.T) {
req, err := http.NewRequest("GET", "/static/index.js", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(StaticHandler)
handler.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
expected := "text/javascript; charset=utf-8"
if rr.Header().Get("Content-Type") != expected {
t.Errorf("handler returned unexpected Content-Type: got %v want %v",
rr.Header().Get("Content-Type"), expected)
}
}
当我在本地运行它时,检查 Content-Type 的测试用例失败:
TestStaticHandlerServeJS: main_test.go:27: handler returned unexpected Content-Type: got application/javascript want text/javascript; charset=utf-8
我还可以在浏览器中确认该文件确实是使用 Mime 类型“application/javascript”提供的,就像它在 Go 1.13 中一样。
当我使用官方镜像在 Docker 容器上运行这个测试时golang:1.14.0-alpine3.11
,这个测试通过了,它反映了mime
包的变化行为。
因此,我留下了一个在本地失败并通过容器的测试用例。我只在本地维护了一个 Go 版本,1.14
就像我上面展示的那样。mime
我的本地 Go 安装程序的包行为不同的原因可能是什么?
解决方案
这对我来说也很有趣,我也有和你一样的行为 - go 1.14 在我的 mashine (macOs catalina) 应用程序/javascript 上交付,而不是 text/javascript。我调试了程序,在 mime 包的 type.go 中发现了这个函数:
func initMime() {
if fn := testInitMime; fn != nil {
fn()
} else {
setMimeTypes(builtinTypesLower, builtinTypesLower)
osInitMime()
}
}
else 块中正在发生有趣的事情。js
在设置为扩展分配给的builtInTypes 后,将text/javascript
文件扩展分配给内容类型的操作系统特定分配,这会覆盖内置分配。在 mac 上,它将文件 type_unix.go where files
"/etc/mime.types",
"/etc/apache2/mime.types",
"/etc/apache/mime.types",
经测试可用,在我的情况下/etc/apache2/mime.types
,操作系统中存在一个文件,它包含...令人惊讶的一行
application/javascript js
并且此行覆盖了 .js 扩展的 go 内置定义,并导致Content-Type: application/javascript
交付给客户端并导致您的测试失败。
推荐阅读
- plot - 绘制连接的 netCDF 并没有给出想要的图
- python - 将 dict 写入不反映在 IDE 之外的外部 .json 文件
- oracle-sqldeveloper - Oracle 数据库 SQL 开发人员 - 错误 - 删除表
- azure-eventhub - 天蓝色事件中心捕获与自定义函数
- typescript - 打字稿:如何确保对象类型中的所有键都在声明的枚举中?
- c# - cant delete file after programmatically creation
- python - 如何在熊猫数据框中仅获取行*并且仅*具有给定值(或值集)的列
- mongodb - 搜索解决方案 Mongodb 查找和过滤字段
- swift - 使用 .onTapGesture 实现细节屏幕
- bash - `wget -i files.txt` 在 VPS 上给出 Scheme Missing 错误