File: sockethandler.go

package info (click to toggle)
golang-github-siddontang-go 0.0~git20170517.0.cb568a3-4
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 484 kB
  • sloc: makefile: 3
file content (65 lines) | stat: -rw-r--r-- 1,115 bytes parent folder | download | duplicates (2)
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 log

import (
	"encoding/binary"
	"net"
	"time"
)

//SocketHandler writes log to a connectionl.
//Network protocol is simple: log length + log | log length + log. log length is uint32, bigendian.
//you must implement your own log server, maybe you can use logd instead simply.
type SocketHandler struct {
	c        net.Conn
	protocol string
	addr     string
}

func NewSocketHandler(protocol string, addr string) (*SocketHandler, error) {
	s := new(SocketHandler)

	s.protocol = protocol
	s.addr = addr

	return s, nil
}

func (h *SocketHandler) Write(p []byte) (n int, err error) {
	if err = h.connect(); err != nil {
		return
	}

	buf := make([]byte, len(p)+4)

	binary.BigEndian.PutUint32(buf, uint32(len(p)))

	copy(buf[4:], p)

	n, err = h.c.Write(buf)
	if err != nil {
		h.c.Close()
		h.c = nil
	}
	return
}

func (h *SocketHandler) Close() error {
	if h.c != nil {
		h.c.Close()
	}
	return nil
}

func (h *SocketHandler) connect() error {
	if h.c != nil {
		return nil
	}

	var err error
	h.c, err = net.DialTimeout(h.protocol, h.addr, 20*time.Second)
	if err != nil {
		return err
	}

	return nil
}