简体   繁体   English

在golang HTTP FileServer的Content-Type标头上设置'charset'属性

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

I've got an issue when testing a golang web app. 测试golang网络应用程序时出现问题。 In the deployed version, nginx fronts the application and explicitly sets charset utf8; 在部署的版本中,nginx在应用程序的前面,并显式设置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. 在测试中,我直接打了golang应用程序,这里的内容类型没有字符集。 This is causing problems when trying to serve libraries like d3 which has lines like: 尝试提供类似d3这样的库时,这会导致问题:

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: 由于golang未指定字符集,因此这些字符在chrome中呈现为:

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? 使golang http服务器在HTTP标头上输出charset = utf8声明的最佳方法是什么?

FileServer calls mime.TypeByExtension to get the content type. FileServer调用mime.TypeByExtension以获取内容类型。 If no type is registered for the extension, then FileServer calls http.DetectContentType to guess the type from the contents of the file. 如果没有为扩展名注册任何类型,则FileServer调用http.DetectContentType从文件的内容中猜测类型。

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. 如果文本/内容类型未指定字符集参数,则mime包会自动将“ charset = utf-8”参数添加到内容类型。

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

If the system mime.types entry is missing or incorrect, then call mime.AddExtensionType to override the system setting. 如果系统mime.types条目丢失或不正确,请调用mime.AddExtensionType以覆盖系统设置。 This can be called once before any content is served. 可以在提供任何内容之前调用一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM