我已将本地Go版本从1.13
升级到1.14
,然后通过使用go mod
进行重新初始化更新了我正在处理的项目。
本地:
$ go version
go version go1.14 linux/amd64
我项目的go.mod
:
module example-project
go 1.14
[Go mime
中的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中一样。
[当我使用正式的golang:1.14.0-alpine3.11
镜像在Docker容器上运行此测试时,此测试通过,并且反映了mime
软件包的更改行为。
因此,我剩下了一个在本地失败并通过容器的测试用例。我在本地仅维护一个版本的Go,即上面显示的1.14
。我的本地Go安装的mime
软件包的行为不同可能是什么原因?
对我来说也很有趣,我的行为也和您一样-在我的mashine(macOs catalina)应用程序/ javascript(而不是文本/ javascript)上发布1.14。我调试了程序,并在mime包的type.go中找到了此功能:
func initMime() {
if fn := testInitMime; fn != nil {
fn()
} else {
setMimeTypes(builtinTypesLower, builtinTypesLower)
osInitMime()
}
}
有趣的东西在else块中进行。在设置了将扩展名js
分配给text/javascript
的BuiltInTypes之后,文件扩展名被分配给内容类型,这将覆盖内置分配。在Mac上,它将转到文件type_unix.go,其中文件
"/etc/mime.types",
"/etc/apache2/mime.types",
"/etc/apache/mime.types",
经过测试可以使用,在我的情况下,文件/etc/apache2/mime.types
存在于操作系统中,并且包含...令人惊讶的一行application / javascript js并且此行覆盖了.js扩展的go内置定义,并导致Content-Type: application/javascript
被传递给客户端,并导致测试失败。