forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuds.go
45 lines (35 loc) · 905 Bytes
/
uds.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
//go:build !windows
package server
import (
"net"
"net/http"
"os"
"github.com/evcc-io/evcc/cmd/shutdown"
"github.com/evcc-io/evcc/core/site"
)
// SocketPath is the unix domain socket path
const SocketPath = "/tmp/evcc"
// removeIfExists deletes file if it exists or fails
func removeIfExists(file string) {
if _, err := os.Stat(file); err == nil {
if err := os.RemoveAll(file); err != nil {
log.FATAL.Fatal(err)
}
}
}
// HealthListener attaches listener to unix domain socket and runs listener
func HealthListener(site site.API) {
removeIfExists(SocketPath)
l, err := net.Listen("unix", SocketPath)
if err != nil {
log.FATAL.Fatal(err)
}
mux := http.NewServeMux()
httpd := http.Server{Handler: mux}
mux.HandleFunc("/health", healthHandler(site))
go func() { _ = httpd.Serve(l) }()
shutdown.Register(func() {
_ = l.Close()
removeIfExists(SocketPath) // cleanup
})
}