等待io.Writer被写入的Golang代码。

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

golang wait for io.Writer to be written to

问题

http.Server 类型位于 golang 标准库的 net/http 包中,它有一个名为 ErrorLog 的字段,类型为 log.Logger

这是我在 http.Server 中设置 ErrorLog 的方式:

// 设置 HTTP 服务器
server = &http.Server{
	Addr:      getPortFromConfig(),
	Handler:   handler,
	ErrorLog:  log.New(io.MultiWriter(stdout, fileout), "", 1),
}

在这里,io.MultiWriter() 函数创建了一个新的 io.Writer,它将把所有从我的 http.Server 写入的内容复制到文件和标准输出(stdout)。它的工作非常好。

然而,我想在写入文件之前拦截数据并进行格式化。

如何实现这一点呢?

英文:

The http.Server type in the golang standard net/http package has a field named ErrorLog, which is of type log.Logger.

This is how ErrorLog is set up in my http.Server:

// set up HTTP server
server = &http.Server{
	Addr:      getPortFromConfig(),
	Handler:   handler,
	ErrorLog:  log.New(io.MultiWriter(stdout, fileout), "", 1),
}

So here, the io.MultiWriter() function creates a new io.Writer that will copy all writes from my http.Server into a file as well as stdout. It works like a charm.

However, I would like to intercept the data and format it before it is written to the file.

How is it possible to do this?

答案1

得分: 1

你可以创建一个自己的写入器,实现"Write([]byte) error"方法。
当你创建这个写入器时,将文件写入器作为参数传递给它。
每当你的写入器接收到数据时,它会对数据进行格式化,然后调用文件写入器的"Write"方法。
类似于:

type MyFormatter struct {
       fileWriter io.Writer
 }

 func (m *MyFormatter) Write(buf []byte) error {
       formattedBytes := FormatBytes(buf)
       m.fileWriter.Write(formattedBytes)
 }

这段代码没有经过测试,只是伪代码!

编辑:你甚至可以使用嵌入式写入器

type MyFormatter struct {
       io.Writer
 }

 func (m *MyFormatter) Write(buf []byte) error {
       formattedBytes := FormatBytes(buf)
       m.Writer.Write(formattedBytes)
 }
英文:

You can create your own writer which implements "Write([]byte) error".
When you create this writer, you give him the file writer as arguments.
Each time your writer receive something, it formats it and then calls the "Write" method on the file writer.
Something like :

type MyFormatter struct {
       fileWriter io.Writer
 }

 func (m *MyFormatter) Write(buf []byte) error {
       formattedBytes := FormatBytes(buf)
       m.fileWriter.Write(formattedBytes)
 }

Haven't tested that code, it is only pseudo code!

EDIT: You can even use embedded writer

type MyFormatter struct {
       io.Writer
 }

 func (m *MyFormatter) Write(buf []byte) error {
       formattedBytes := FormatBytes(buf)
       m.Writer.Write(formattedBytes)
 }

huangapple
  • 本文由 发表于 2015年11月12日 16:09:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/33666836.html
匿名

发表评论

匿名网友

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

确定