/
syslog_http.go
89 lines (74 loc) · 1.5 KB
/
syslog_http.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package syslog
import (
"bytes"
"compress/gzip"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
)
const QueryInGzip = "in_gzip"
type HttpWriter struct {
url string
inGzip bool
}
func HttpDial(addr string) (*HttpWriter, error) {
u, err := url.Parse(addr)
if err != nil {
return nil, err
}
inGzip := false
inGzipRaw := u.Query().Get(QueryInGzip)
if inGzipRaw != "" {
inGzip, err = strconv.ParseBool(inGzipRaw)
if err != nil {
inGzip = true
}
}
u.Query().Del(QueryInGzip)
return &HttpWriter{
url: u.String(),
inGzip: inGzip,
}, nil
}
func (t *HttpWriter) Write(b []byte) (int, error) {
if t.inGzip {
return len(b), t.writeGzip(b)
}
return len(b), t.writePlain(b)
}
func (t *HttpWriter) writeGzip(b []byte) error {
buf := &bytes.Buffer{}
gw := gzip.NewWriter(buf)
gw.Write(b)
gw.Flush()
gw.Close()
return t.post("gzip", buf)
}
func (t *HttpWriter) writePlain(b []byte) error {
return t.post("", bytes.NewBuffer(b))
}
func (t *HttpWriter) post(contentEncoding string, r io.Reader) error {
req, err := http.NewRequest("POST", t.url, r)
if err != nil {
return err
}
req.Header.Add("Content-Type", "text/plain")
if contentEncoding != "" {
req.Header.Add("Content-Encoding", contentEncoding)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 400 {
b, _ := io.ReadAll(resp.Body)
return fmt.Errorf(string(b))
}
return nil
}
func (t *HttpWriter) Close() error {
return nil
}