dsjfrkvn818747 2015-11-12 08:09
浏览 167

golang等待io.Writer被写入

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条回答 默认 最新

  • dtnbjjq51949 2015-11-12 08:21
    关注

    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)
     }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用