summaryrefslogtreecommitdiff
path: root/internal/server.go
blob: 38e478c1079549d90813a5abf54fc0f4c3fb51c6 (plain)
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package internal

import (
	"context"
	"net"
	"sync"

	"tildegit.org/tjp/gus/logging"
)

type Server struct {
	Ctx         context.Context
	Cancel      context.CancelFunc
	Wg          *sync.WaitGroup
	Listener    net.Listener
	HandleConn  connHandler
	ErrorLog    logging.Logger
	Host        string
	NetworkAddr net.Addr
}

type connHandler func(net.Conn)

func NewServer(
	ctx context.Context,
	hostname string,
	network string,
	address string,
	errorLog logging.Logger,
	handleConn connHandler,
) (Server, error) {
	listener, err := net.Listen(network, address)
	if err != nil {
		return Server{}, err
	}

	networkAddr := listener.Addr()
	ctx, cancel := context.WithCancel(ctx)

	return Server{
		Ctx:         ctx,
		Cancel:      cancel,
		Wg:          &sync.WaitGroup{},
		Listener:    listener,
		HandleConn:  handleConn,
		ErrorLog:    errorLog,
		Host:        hostname,
		NetworkAddr: networkAddr,
	}, nil
}

func (s *Server) Serve() error {
	s.Wg.Add(1)
	defer s.Wg.Done()

	s.propagateClose()

	for {
		conn, err := s.Listener.Accept()
		if err != nil {
			if s.Closed() {
				err = nil
			} else {
				_ = s.ErrorLog.Log("msg", "accept error", "error", err)
			}

			return err
		}

		s.Wg.Add(1)
		go func() {
			defer s.Wg.Done()
			defer func() {
				_ = conn.Close()
			}()

			s.HandleConn(conn)
		}()
	}
}

func (s *Server) Hostname() string {
	host, _, _ := net.SplitHostPort(s.Host)
	return host
}

func (s *Server) Port() string {
	_, port, _ := net.SplitHostPort(s.Host)
	return port
}

func (s *Server) Network() string {
	return s.NetworkAddr.Network()
}

func (s *Server) Address() string {
	return s.NetworkAddr.String()
}

func (s *Server) Close() {
	s.Cancel()
	s.Wg.Wait()
}

func (s *Server) LogError(keyvals ...any) error {
	return s.ErrorLog.Log(keyvals...)
}

func (s *Server) Closed() bool {
	select {
	case <-s.Ctx.Done():
		return true
	default:
		return false
	}
}

func (s *Server) propagateClose() {
	s.Wg.Add(1)
	go func() {
		defer s.Wg.Done()

		<-s.Ctx.Done()
		_ = s.Listener.Close()
	}()
}