Home > OS >  Golang fileserver setting content-type differently on linux and macos
Golang fileserver setting content-type differently on linux and macos

Time:11-28

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.

CodePudding user response:

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.

  • Related