3

I've got an issue when testing a golang web app. In the deployed version, nginx fronts the application and explicitly sets charset utf8; so that all textual content types are appended with a charset declaration.

In testing, I'm hitting the golang application directly, and here the content type does not have a charset set. This is causing problems when trying to serve libraries like d3 which has lines like:

var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π;

Because golang doesn't specify the charset, these are rendered in chrome as:

var ε = 1e-6, ε2 = ε * ε....

What's the best way of getting the golang http server to output the charset=utf8 declaration on the HTTP headers?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
growse
  • 3,554
  • 9
  • 43
  • 66
  • 2
    I assume you mean the Go HTTP server, not Chrome? Just `w.Header().Set("Content-Type", "text/html; charset=utf-8")` (if that's the content type) in the relevant handlers, and/or in middleware to apply it to multiple handlers. – elithrar Aug 30 '15 at 23:46
  • Erk, fixed the typo. I'm using the fileserver to serve a directory of different files and mimetypes, so setting it manually might not really work, unless I reimplement the existing content type sniffing. – growse Aug 31 '15 at 10:53

1 Answers1

4

FileServer calls mime.TypeByExtension to get the content type. If no type is registered for the extension, then FileServer calls http.DetectContentType to guess the type from the contents of the file.

If a text/ content type does not specify a charset parameter, then the mime package automatically adds the 'charset=utf-8' parameter to the content type.

To debug this problem, check to see if the system mime.types file specifies a content type for the file extension and that the charset parameter is'charset=utf-8' or the charset parameter is not set.

If the system mime.types entry is missing or incorrect, then call mime.AddExtensionType to override the system setting. This can be called once before any content is served.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
  • I tried to `mime.AddExtensionType(".js","application/javascript; charset=utf8")` as the first line in `main()` but it made no difference. Also, while I'm testing on OSX, doing the same test on linux resulted in the `js` file being just served as `application/javascript` without a charset parameter. – growse Aug 31 '15 at 11:02
  • *edit* this program seems to still serve javascript as `application/javascript` on a mac: http://play.golang.org/p/AIWPjrOGOt – growse Aug 31 '15 at 11:10
  • Ok, that's weird - it works for me now as well. I think I was running into a chrome caching issue. – growse Aug 31 '15 at 14:10