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.

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

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错