在golang HTTP FileServer的Content-Type头中设置'charset'属性 [英] Setting the 'charset' property on the Content-Type header in the golang HTTP FileServer

查看:2506
本文介绍了在golang HTTP FileServer的Content-Type头中设置'charset'属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在测试golang网络应用时遇到问题。在部署版本中,nginx面向应用程序,并显式设置 charset utf8; ,以便所有文本内容类型都附加一个charset声明。



在测试中,我直接打golang应用程序,这里的内容类型没有设置字符集。这在尝试提供像 d3 这样的图书馆时出现问题其具有如下线:

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

因为golang没有指定字符集,所以它们在chrome中显示为:

  varÎμ= 1e-6,Îμ2=Îμ*Îμ.... 

使golang http服务器在HTTP头上输出charset = utf8声明的最好方法是什么?

解决方案

FileServer调用 mime.TypeByExtension 获取内容类型。如果未为扩展注册任何类型,则FileServer将调用 http.DetectContentType 以从



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



要调试此问题,请检查系统mime.types文件是否指定文件扩展名的内容类型,并且charset参数是charset = 如果系统mime.types条目缺失或不正确,则调用 godoc.org/mime#AddExtensionTyperel =nofollow> mime.AddExtensionType 以覆盖系统设置。在投放任何内容之前,可以调用一次。


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?

解决方案

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.

这篇关于在golang HTTP FileServer的Content-Type头中设置'charset'属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆