-
Notifications
You must be signed in to change notification settings - Fork 5
/
urlwriter.go
65 lines (57 loc) · 1.52 KB
/
urlwriter.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
58
59
60
61
62
63
64
65
package apt
import (
"bytes"
"io"
"net/url"
"strings"
)
// URLWriter is a io.Writer which only writes URLS
type URLWriter struct {
writer io.Writer
buffer bytes.Buffer
prefix string
}
// NewURLWriter creates a new URLWriter instance.
func NewURLWriter(w io.Writer, prefix string) *URLWriter {
return &URLWriter{
writer: w,
buffer: bytes.Buffer{},
prefix: prefix,
}
}
// Write implements the io.Writer interface.
//
// Write buffers data until it hits a newline, at which point it checks if the
// buffered data is a URL. If it is, it writes that URL to the MessageWriter
// instance it was created with, along with the prefix prepended.
func (uw *URLWriter) Write(data []byte) (int, error) {
start := 0
for i, b := range data {
// If we hit a newline, copy data[start:i] into the buffer and commit
if b == byte('\n') {
uw.buffer.Write(data[start:i])
uw.commit()
start = i + 1
}
}
uw.buffer.Write(data[start:])
return len(data), nil
}
// commit takes a line from the buffer and checks if it is a url. If it is,
// then it writes the URL using the message writer.
func (uw *URLWriter) commit() {
// Pull data from buffer, trim off spaces
line := strings.TrimSpace(uw.buffer.String())
if strings.HasPrefix(line, "http") {
// Check if we have a URL, and if so print it
_, err := url.Parse(line)
if err == nil {
uw.writer.Write([]byte("\r"))
uw.writer.Write([]byte(uw.prefix))
uw.writer.Write([]byte(line))
uw.writer.Write([]byte("\n"))
}
}
// Clear the buffer regardless
uw.buffer.Reset()
}