【问题标题】:Passing string containing "%" to http.ResponseWriter causes variable missing将包含“%”的字符串传递给 http.ResponseWriter 会导致变量丢失
【发布时间】:2018-04-01 04:45:45
【问题描述】:

w 是 http.ResponseWriter 类型

这很好:

fmt.Fprintf(w, statusPercentage + " " + mostUpToDateStatusDownloaded + "/"+ mostUpToDateStatusOverallData)

输出:100 488 MB/488 MB

这会导致问题:

fmt.Fprintf(w, statusPercentage + "% " + mostUpToDateStatusDownloaded + "/"+ mostUpToDateStatusOverallData)

输出:100%! (缺失)MB/488 MB

【问题讨论】:

标签: string http go


【解决方案1】:

如果您不进行任何字符串格式化,为什么还要使用fmt.Fprintf?只需改用fmt.Fprint

【讨论】:

    【解决方案2】:

    % 是一个特殊的占位符符号。如果您想将其作为符号本身放入字符串中 - 复制它。喜欢:

    fmt.Fprintf(w, "Growth %v %%", "50")
    

    输出:

    Growth 50%
    

    【讨论】:

    • 您的代码使用了错误的引号。更具体地说:invalid identifier character U+201C '“'invalid identifier character U+201D '”'
    • 抱歉,我是从手机发送的 - 看起来自动更正决定更改符号。
    【解决方案3】:

    使用任意应用程序字符串作为 fmt.Fprintf 及其朋友的格式说明符通常不是一个好习惯。应用程序应使用固定格式的字符串或将字符串转换为字节并将字节直接写入响应。

    以下是使用格式字符串的方法:

    // note that '%' is quoted as %%
    fmt.Fprintf(w, "%s%% %s/%s", statusPercentage, mostUpToDateStatusDownloaded, mostUpToDateStatusOverallData)
    

    以下是如何跳过格式并直接写入响应:

    io.WriteString(w, statusPercentage + "% " + mostUpToDateStatusDownloaded + "/"+ mostUpToDateStatusOverallData)
    

    【讨论】:

      猜你喜欢
      • 2021-10-04
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      • 2011-08-21
      • 2019-12-04
      相关资源
      最近更新 更多