ChicagoBoss里直接在Controller里面使用中文

2021-01-26 11:01:54 浏览数 (1)

如果直接在controller里面使用中文,像下面这样:

代码语言:javascript复制
-module(snooker_main_controller, [Req]).
-compile(export_all).

index('GET', []) ->

    {ok, [{greeting, "中文测试!"}]}.

会报类似下面的错误

代码语言:javascript复制
http process <0.5215.0> has died with reason: {badarg,
                                               [{erlang,list_to_binary,
                                                 [[<<"<!DOCTYPE html>n<html lang="en">n<head>n<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />n<title>">>,
                                                   <<230,150,175,232,175,186,
                                                     229,174,162,32,45,32,228,
                                                     184,128,232,181,183,230,
                                                     150,175,232,175,186,229,
                                                     174,162>>,

原因在于erlang的源文件都是只支持latin字符集的,只要是*erl的文件,都是这样,所以出现unicode字符的话,都会类似的错误。所有的unicode字符都应该由变量传递或者进行encode

解决方法: 修改controller源文件

代码语言:javascript复制
-module(snooker_main_controller, [Req]).
-compile(export_all).

index('GET', []) ->

    {ok, [{greeting, unicode:characters_to_binary("中文测试!", utf8, utf8)}]}.

这样就可以了。

unicode:characters_to_binary的用法:

代码语言:javascript复制
characters_to_binary(Data, InEncoding, OutEncoding) -> Result

Types:

Data = latin1_chardata() | chardata() | external_chardata()
InEncoding = OutEncoding = encoding()
Result = binary()
       | {error, binary(), RestData}
       | {incomplete, binary(), binary()}
RestData = latin1_chardata() | chardata() | external_chardata()

  • Previous 在Ubuntu Oneiric下从源代码安装 Erlang R15B
  • Next 如何在Erlang的List中移除element?

0 人点赞