-
Notifications
You must be signed in to change notification settings - Fork 3
/
state.go
71 lines (67 loc) · 1.31 KB
/
state.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
package tcpproxy
import (
"encoding/json"
"io"
"log"
"os"
)
// for marshalling/unmarshalling json
type serverState struct {
// proxy incoming connections to this address
RemoteAddress string
}
func (p *Proxy) loadState() {
if p.StatePath == "" {
return
}
f, err := os.Open(p.StatePath)
if os.IsNotExist(err) {
p.saveState()
return
}
if err != nil {
log.Fatalln("cannot open state file:", err)
}
size, err := f.Seek(0, io.SeekEnd)
if err != nil {
log.Fatalln("cannot seek state file:", err)
}
_, err = f.Seek(0, io.SeekStart)
if err != nil {
log.Fatalln("cannot seek state file:", err)
}
if size == 0 {
f.Close()
p.saveState()
return
}
var s serverState
err = json.NewDecoder(f).Decode(&s)
if err != nil {
log.Fatalln("cannot read state file:", err)
}
p.remote.setAddr(s.RemoteAddress)
log.Println("loaded remote address:", s.RemoteAddress)
f.Close()
}
func (p *Proxy) saveState() {
if p.StatePath == "" {
return
}
f, err := os.Create(p.StatePath)
if err != nil {
log.Fatalln("cannot open state file:", err)
}
defer f.Close()
s := serverState{RemoteAddress: p.remote.getAddr()}
err = json.NewEncoder(f).Encode(s)
if err != nil {
log.Println("cannot write state file:", err)
return
}
err = f.Sync()
if err != nil {
log.Println("cannot sync state file:", err)
return
}
}