Golang文件服务器在Linux和macOS上设置Content-Type不同。

huangapple go评论95阅读模式
英文:

Golang fileserver setting content-type differently on linux and macos

问题

我正在使用http.FileServer在我的Web服务中,当我尝试从中提供一个JavaScript文件时,在Linux(debian 11)上会得到一个text/javascript; charset=utf-8的内容类型头,但在MacOS 13上是application/javascript

Linux上的Go版本是1.19.1,而MacOS上是1.19.3。在这两台机器上,我在Web服务运行的环境中设置了LANG=en_GB.UTF-8

有趣的是,当提供其他文本文件时,例如HTML文件,我会在**MacOS和Linux上都得到text/html; charset=utf-8

这是什么原因呢?这导致我的单元测试在MacOS上失败,我更希望测试完整的内容类型,包括字符集。

英文:

I am using the http.FileServer in my web service, and when I try serving a javascript file from it, I will get a content-type header of text/javascript; charset=utf-8 on Linux (debian 11), but application/javascript on MacOS 13.

Go version is 1.19.1 on linux, and 1.19.3 on MacOS. On both machines I set LANG=en_GB.UTF-8 in the environment the web service runs in.

Interestingly, when serving other text files, e.g. a HTML file, I will get text/html; charset=utf-8 on both MacOS and Linux.

What is the reason for this? It makes my unit tests fail on MacOS, and I would prefer to test for the full content-type including character set.

答案1

得分: 1

http.FileServer使用文件名的扩展名来确定Content-Type,如果未设置的话。这个过程中会调用mime.TypeByExtension()方法。

mime.TypeByExtension()的文档说明称,系统的MIME.info数据库会增加映射关系。这些数据库在Linux和MacOS之间可能是不同的。

@Andrei Vasilev指出,你可以使用AddExtensionType()来覆盖默认的MIME类型。

另外,你可以更新相应的本地mime.types文件,使其返回相同的类型。在我的MacOS 12.6.1上,使用go1.19.1 darwin/arm64,我安装了Apache,执行以下代码的返回值为:

mime.TypeByExtension(".js")

来自于/etc/apache2/mime.types文件。

英文:

http.FileServer uses the filename's extension to determine the Content-Type if it's not set. That in turn calls mime.TypeByExtension().

The documentation for mime.TypeByExtension() says that the mapping is augmented by the system's MIME.info database. Those are likely different between Linux and MacOS.

@Andrei Vasilev notes that you can override the default mime types with AddExtensionType().

Alternatively, you could update the appropriate local mime.types file to make them return the same type. On my MacOS 12.6.1 with go1.19.1 darwin/arm64, I have apache installed and the return value of:

mime.TypeByExtension(".js")

is from /etc/apache2/mime.types.

huangapple
  • 本文由 发表于 2022年11月23日 21:12:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/74547356.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定