首页 > 解决方案 > 与官方 Docker 镜像相比,Go Mime 包(1.14)在本地表现不同

问题描述

我已经将我的本地 Go 版本从 升级1.131.14,然后我通过重新初始化使用go mod.

本地:

$ go version
go version go1.14 linux/amd64

go.mod我的项目:

module example-project

go 1.14

mimeGo 1.14中的包中有一个更新,将.js文件的默认类型从 更改application/javascripttext/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 安装程序的包行为不同的原因可能是什么?

标签: gomime-types

解决方案


这对我来说也很有趣,我也有和你一样的行为 - 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交付给客户端并导致您的测试失败。


推荐阅读