如何在Go中防止输出生成,直到所有错误检查完成?

huangapple go评论99阅读模式
英文:

How do you prevent output from being generated in Go until all error checks have completed?

问题

可能是一个简单的问题,但我在请求处理程序函数中延迟输出方面遇到了问题。我在执行模板时使用了"bufio"来写入,而不是使用响应写入器,但似乎缓冲区只能容纳一定量的内容,然后就会输出。我担心它会先输出页面的一部分,然后遇到错误,导致响应不完整和难以理解。确保所有内容都在准备好发布之前保持缓冲的最佳策略是什么?

英文:

Probably a simple question, but I am having issues delaying the output in a request handler function. I'm using "bufio" to write to when I execute my templates instead of the response writer, but it seems like the buffer can only hold so much before it spits things out. I'm concerned that it will spit out part of the page, then encounter an error, leaving an incomplete and unintelligible response. What is the best strategy for ensuring that everything stays buffered until it's ready to be released into the wild?

答案1

得分: 6

如果你想完全缓冲输出,请使用bytes.Buffer,示例代码如下:

var bufferPool = &sync.Pool{
    New: func() interface{} {
        return &bytes.Buffer{}
    },
}

func getBuffer() (buf *bytes.Buffer) {
    return bufferPool.Get().(*bytes.Buffer)
}

func putBuffer(buf *bytes.Buffer) {
    buf.Reset()
    bufferPool.Put(buf)
}

func handler(w http.ResponseWriter, req *http.Request) {
    buf := getBuffer()
    defer putBuffer(buf)
    //....
    fmt.Fprintf(buf, .....)
    buf.WriteTo(w)
}

这段代码使用了bytes.Buffer来缓冲输出。首先,我们创建了一个bufferPool,它是一个sync.Pool类型的对象,用于管理bytes.Buffer对象的池子。getBuffer函数从池子中获取一个bytes.Buffer对象,putBuffer函数将使用完的bytes.Buffer对象放回池子中。

handler函数中,我们通过调用getBuffer函数获取一个bytes.Buffer对象,并在函数结束时通过defer语句调用putBuffer函数将对象放回池子中。在处理过程中,我们可以使用fmt.Fprintf等函数向buf中写入数据,最后通过buf.WriteTo(w)将缓冲的数据写入http.ResponseWriter对象中,完成输出。

英文:

If you want to completely buffer the output use bytes.Buffer instead, example:

var bufferPool = &sync.Pool{
	New: func() interface{} {
		return &bytes.Buffer{}
	},
}

func getBuffer() (buf *bytes.Buffer) {
	return bufferPool.Get().(*bytes.Buffer)
}

func putBuffer(buf *bytes.Buffer) {
	buf.Reset()
	bufferPool.Put(buf)
}


func handler(w http.ResponseWriter, req *http.Request) {
	buf := getBuffer()
	defer putBuffer(buf)
	//....
	fmt.Fprintf(buf, .....)
	buf.WriteTo(w)
}

答案2

得分: 0

你可以使用 bytes.Buffer。

func Handler(w http.ResponseWriter, req *http.Request) {
    tmp, err := template.New("hello").Parse("Hello {{.World}}")
    if err != nil {
        http.Error(w, "Error", 500)
        return
    }

    buf := &bytes.Buffer{}

    if err := tmp.Execute(buf, map[string]string{"World": "World"}); err != nil {
        http.Error(w, "Error", 500)
        return
    }

    w.Write(buf.Bytes())
}
英文:

You could just use a bytes.Buffer

func Handler(w http.ResponseWriter, req *http.Request) {
    tmp, err := template.New("hello").Parse("Hello {{.World}}")
    if err != nil {
        http.Error(w, "Error", 500)
        return
    }

    buf := &bytes.Buffer{}

    if err := tmp.Execute(buf, map[string]string{"World": "World"}); err != nil {
        http.Error(w, "Error", 500)
        return
    }

    w.Write(buf.Bytes())
}

huangapple
  • 本文由 发表于 2014年9月9日 03:44:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/25731953.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定