forked from hsiafan/httpdump
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprinter.go
57 lines (48 loc) · 1.15 KB
/
printer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main
import (
"io"
"os"
)
// Printer output parsed http messages
type Printer struct {
outputQueue chan string
outputFile io.WriteCloser
}
var maxOutputQueueLen = 4096
func newPrinter(outputPath string) *Printer {
var outputFile io.WriteCloser
if outputPath == "" {
outputFile = os.Stdout
} else {
var err error
outputFile, err = os.OpenFile(outputPath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
if err != nil {
panic(err)
}
}
printer := &Printer{outputQueue: make(chan string, maxOutputQueueLen), outputFile: outputFile}
printer.start()
return printer
}
func (printer *Printer) send(msg string) {
if len(printer.outputQueue) == maxOutputQueueLen {
// skip this msg
logger.Warn("too many messages to output, discard current!")
return
}
printer.outputQueue <- msg
}
func (printer *Printer) start() {
printerWaitGroup.Add(1)
go printer.printBackground()
}
func (printer *Printer) printBackground() {
defer printerWaitGroup.Done()
defer printer.outputFile.Close()
for msg := range printer.outputQueue {
_, _ = printer.outputFile.Write([]byte(msg))
}
}
func (printer *Printer) finish() {
close(printer.outputQueue)
}