-
Notifications
You must be signed in to change notification settings - Fork 1
/
callback.go
89 lines (70 loc) · 1.62 KB
/
callback.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 ccu
import (
"fmt"
"io"
"net"
"net/http"
"net/url"
"strconv"
"time"
"github.com/dueckminor/mypi-tools/go/xmlrpc"
)
type HttpHandler struct {
ccuc *CcuClientImpl
}
func resolveHostIp() string {
netInterfaceAddresses, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, netInterfaceAddress := range netInterfaceAddresses {
networkIp, ok := netInterfaceAddress.(*net.IPNet)
if ok && !networkIp.IP.IsLoopback() && networkIp.IP.To4() != nil {
return networkIp.IP.String()
}
}
return ""
}
func (h *HttpHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
body, _ := io.ReadAll(req.Body)
response, err := xmlrpc.HandleMethodCall(body, h.ccuc)
if err == nil {
res.Write(response) // nolint: errcheck
}
}
func (ccuc *CcuClientImpl) GetOwnIP() string {
if len(ccuc.ownIP) == 0 {
ccuc.ownIP = resolveHostIp()
}
return ccuc.ownIP
}
func (ccuc *CcuClientImpl) StartCallbackHandler() error {
httpHandler := &HttpHandler{}
httpHandler.ccuc = ccuc
port := "0"
parsedURI, err := url.Parse(ccuc.uri)
if err == nil {
port = parsedURI.Port()
}
ln, err := net.Listen("tcp", ":"+port)
if err != nil {
return err
}
port = strconv.FormatInt(int64(ln.Addr().(*net.TCPAddr).Port), 10)
ownURL := "http://" + ccuc.GetOwnIP() + ":" + port
ownID := "MYPI-" + ccuc.GetOwnIP() + "-" + port
go http.Serve(ln, httpHandler) // nolint: errcheck
err = ccuc.Init(ownURL, ownID)
if err != nil {
return err
}
go func() {
for {
time.Sleep(15 * time.Minute)
fmt.Println("Init again...")
ccuc.Init(ownURL, ownID) // nolint: errcheck
}
}()
return err
}