douwen9343 2016-02-02 00:59
浏览 155
已采纳

golang html / template ExecuteTemplate错误字节来自哪里?

Background I was trying to write some GZIP middleware for Go, but ran into a problem as http.DetectContentType() was returning text/plain instead of text/html so I tracked it down to the first text being written was some sort or errant byte, that I am still trying to track down. I know there are lots of ways around it, like setting the ContentType explicitly or using a bytes.Buffer when Executing the template and writing all at once, but I really want to find out what is causing this single byte to be written.

Example Here is a very contrived example that shows the same issue https://play.golang.org/p/SSrWP9jLRq

when run you will see the first thing that is printed is: "LEN BYTES: 1 String: "

Suspects It appears, as the example shows, that this line "{{template "header" .}}" within the content template is the culprit, but why would it be outputting this extra content.

Question Does anybody know where this errant byte is coming from? see the html header, footer and content templates in the example.

  • 写回答

1条回答 默认 最新

  • douliao8760 2016-02-02 01:50
    关注

    Because template content starts immediately following the closing braces in the define directive, the root, header and footer templates start with a newline.

    The single newline is written at the start because the template flushes output before invoking a sub-template.

    Change the definitions to start with

    header = `{{define "header"}}<!DOCTYPE html>
    ...
    content = `{{define "root"}}{{template "header" .}}
    

    to eliminate the extra newlines.

    See https://play.golang.org/p/AzD98cD7c0 for a fix.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab在安装时报错 无法找到入口 无法定位程序输入点
  • ¥15 收益高的广告联盟有哪些
  • ¥15 Android Studio webview 的使用问题, 播放器横屏全屏
  • ¥15 删掉jdk后重新下载,Java web所需要的eclipse无法使用
  • ¥15 uniapp正式环境中通过webapi将本地数据推送到设备出现的跨域问题
  • ¥15 xui建立节点,显示错误
  • ¥15 关于#单片机#的问题:开始、复位、十进制的功能可以实现,但是切换八进制的功能无法实现(按下按键也没有效果),把初始状态调成八进制,也是八进制可以实现但是切换到十进制不行(相关搜索:汇编语言|计数器)
  • ¥15 VINS-Mono或Fusion中feature_manager中estimated_depth是特征的深度还是逆深度?
  • ¥15 谷歌浏览器如何备份抖音网页数据
  • ¥15 分别有什么商家下面需要非常多的骑手为它工作?