我有一個Go文本/模板來渲染一個文件,但是我發現很難在保留輸出中的換行符的同時乾淨地構造模板。刪除一個golang作家的連續空行
我想在模板中增加額外的不必要的換行符,使其更具可讀性,但將它們從輸出中去除。任何比正常段落中斷更多的換行符都應該縮寫爲正常的段落中斷,例如,
lines with
too many breaks should become lines with
normal paragraph breaks.
字符串可能太大而不能安全地存儲在內存中,所以我想保留它作爲輸出流。
我第一次嘗試:
type condensingWriter struct {
writer io.Writer
lastLineIsEmpty bool
}
func (c condensingWriter) Write(b []byte) (n int, err error){
thisLineIsEmpty := strings.TrimSpace(string(b)) == ""
defer func(){
c.lastLineIsEmpty = thisLineIsEmpty
}()
if c.lastLineIsEmpty && thisLineIsEmpty{
return 0, nil
} else {
return c.writer.Write(b)
}
}
這不工作,因爲我天真地認爲,這將緩衝的換行符,但事實並非如此。
有關如何使其發揮作用的任何建議?
也許用這個遊戲作爲一個起點: – Alex 2015-02-05 20:29:27
HTTP ://play.golang.org/p/wNtHFHobhm – Alex 2015-02-05 20:35:04
定義太大。 – 2015-02-05 20:41:18