在golang的HTTP FileServer中,设置Content-Type头部的’charset’属性。

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

Setting the 'charset' property on the Content-Type header in the golang HTTP FileServer

问题

我在测试一个 Golang Web 应用时遇到了一个问题。在部署版本中,Nginx 作为应用的前端,明确设置了 charset utf8;,以便为所有文本内容类型添加字符集声明。

在测试中,我直接访问 Golang 应用程序,这里的内容类型没有设置字符集。这在尝试提供类似于 <a href="https://github.com/mbostock/d3/blob/v3.5.6/d3.js#L1261">d3</a> 这样的库时会导致问题,其中包含以下代码行:

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

由于 Golang 没有指定字符集,这些代码在 Chrome 中呈现为:

var &#206;&#181; = 1e-6, &#206;&#181;2 = &#206;&#181; * &#206;&#181;....

如何让 Golang HTTP 服务器在 HTTP 头中输出 charset=utf8 声明的最佳方法是什么?

英文:

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 <a href="https://github.com/mbostock/d3/blob/v3.5.6/d3.js#L1261">d3</a> 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 &#206;&#181; = 1e-6, &#206;&#181;2 = &#206;&#181; * &#206;&#181;....

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

答案1

得分: 4

FileServer调用mime.TypeByExtension来获取内容类型。如果没有为该扩展名注册类型,则FileServer调用http.DetectContentType来从文件内容中猜测类型。

如果text/内容类型没有指定charset参数,则mime包会自动将'charset=utf-8'参数添加到内容类型中。

要调试此问题,请检查系统mime.types文件是否为文件扩展名指定了内容类型,并且charset参数为'charset=utf-8'或未设置charset参数。

如果系统mime.types条目缺失或不正确,则调用mime.AddExtensionType来覆盖系统设置。这可以在提供任何内容之前调用一次。

英文:

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.

huangapple
  • 本文由 发表于 2015年8月31日 05:46:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/32301463.html
匿名

发表评论

匿名网友

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

确定