bvpx
bvpx

Reputation: 1287

golang wait for io.Writer to be written to

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?

Upvotes: 1

Views: 1226

Answers (1)

Nikkolasg
Nikkolasg

Reputation: 454

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

Upvotes: 2

Related Questions