-
Notifications
You must be signed in to change notification settings - Fork 23
/
httpd.go
71 lines (58 loc) · 1.47 KB
/
httpd.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 main
import (
"errors"
"log/slog"
"net"
"net/http"
"os"
"strings"
"time"
"github.com/bouncepaw/mycorrhiza/internal/cfg"
)
func serveHTTP(handler http.Handler) (err error) {
server := &http.Server{
ReadTimeout: 300 * time.Second,
WriteTimeout: 300 * time.Second,
IdleTimeout: 300 * time.Second,
Handler: handler,
}
if strings.HasPrefix(cfg.ListenAddr, "/") {
err = startUnixSocketServer(server, cfg.ListenAddr)
} else {
server.Addr = cfg.ListenAddr
err = startHTTPServer(server)
}
return err
}
func startUnixSocketServer(server *http.Server, socketPath string) error {
err := os.Remove(socketPath)
if err != nil {
return err
}
listener, err := net.Listen("unix", socketPath)
if err != nil {
slog.Error("Failed to start the server", "err", err)
return err
}
defer func(listener net.Listener) {
_ = listener.Close()
}(listener)
if err := os.Chmod(socketPath, 0666); err != nil {
slog.Error("Failed to set socket permissions", "err", err)
return err
}
slog.Info("Listening Unix socket", "addr", socketPath)
if err := server.Serve(listener); !errors.Is(err, http.ErrServerClosed) {
slog.Error("Failed to start the server", "err", err)
return err
}
return nil
}
func startHTTPServer(server *http.Server) error {
slog.Info("Listening over HTTP", "addr", server.Addr)
if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
slog.Error("Failed to start the server", "err", err)
return err
}
return nil
}