-
Notifications
You must be signed in to change notification settings - Fork 4
/
lib.go
111 lines (98 loc) · 2.04 KB
/
lib.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"encoding/binary"
"fmt"
"io"
"net/url"
"strings"
)
const (
socketPath = "/tmp/governator.sock"
AppName = "governator"
)
type resp uint8
const (
respEnd resp = iota
respOk
respErr
)
func encodeString(w io.Writer, s string) error {
length := uint32(len(s))
if err := codecWrite(w, length); err != nil {
return err
}
if _, err := io.WriteString(w, s); err != nil {
return err
}
return nil
}
func decodeString(r io.Reader) (string, error) {
var length uint32
if err := codecRead(r, &length); err != nil {
return "", err
}
s := make([]byte, length)
if _, err := io.ReadFull(r, s); err != nil {
return "", err
}
return string(s), nil
}
func encodeArgs(w io.Writer, args []string) error {
count := int32(len(args))
codecWrite(w, count)
for _, v := range args {
if err := encodeString(w, v); err != nil {
return err
}
}
return nil
}
func decodeArgs(r io.Reader) ([]string, error) {
var count uint32
if err := codecRead(r, &count); err != nil {
return nil, err
}
args := make([]string, int(count))
for ii := 0; ii < int(count); ii++ {
s, err := decodeString(r)
if err != nil {
return nil, err
}
args[ii] = s
}
return args, nil
}
func encodeResponse(w io.Writer, r resp, s string) error {
if w != nil {
if err := codecWrite(w, r); err != nil {
return err
}
if err := encodeString(w, s); err != nil {
return err
}
}
return nil
}
func decodeResponse(r io.Reader) (resp, string, error) {
var re resp
if err := codecRead(r, &re); err != nil {
return 0, "", err
}
s, err := decodeString(r)
return re, s, err
}
func codecRead(r io.Reader, out interface{}) error {
return binary.Read(r, binary.BigEndian, out)
}
func codecWrite(w io.Writer, in interface{}) error {
return binary.Write(w, binary.BigEndian, in)
}
func parseServerAddr(addr string) (string, string, error) {
u, err := url.Parse(addr)
if err != nil {
return "", "", fmt.Errorf("invalid server URL %q: %s", addr, err)
}
scheme := u.Scheme
u.Scheme = ""
return scheme, strings.TrimPrefix(u.String(), "//"), nil
}