-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
95 lines (82 loc) · 1.83 KB
/
server.go
File metadata and controls
95 lines (82 loc) · 1.83 KB
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
// SPDX-License-Identifier: MIT
//go:build samples
package server
import (
"errors"
"fmt"
"github.com/spandigital/with"
"time"
)
type Server interface {
Run()
}
type Options struct {
Host string
Port int
Timeout time.Duration
}
func (o *Options) Validate() (err error) {
switch {
case o.Host == "":
err = errors.New("Host is required")
case o.Port == 0:
err = errors.New("Port is required")
case !(o.Port > 0 && o.Port < 65535):
err = errors.New("Port must be between 1 and 65535")
case o.Timeout == 0:
err = errors.New("Timeout is required")
}
return
}
func WithHost(host string) with.Func[Options] {
return func(options *Options) (err error) {
options.Host = host
return
}
}
func WithPort(port int) with.Func[Options] {
return func(options *Options) (err error) {
switch {
case port == 0:
return errors.New("Port is required")
case !(port > 0 && port < 65535):
return errors.New("Port must be between 1 and 65535")
}
options.Port = port
return
}
}
func WithTimeout(timeout time.Duration) with.Func[Options] {
return func(options *Options) (err error) {
options.Timeout = timeout
return
}
}
type server struct {
host string
port int
timeout time.Duration
}
func NewServer(withOptions ...with.Func[Options]) (server *server, err error) {
o := &Options{}
if err = with.DefaultThenAddWith(o, withOptions); err == nil {
server = newServer(o)
}
return
}
func NewServerFromOptions(options *Options, withOptions ...with.Func[Options]) (server *server, err error) {
if err = with.AddWith(options, withOptions); err == nil {
server = newServer(options)
}
return
}
func newServer(options *Options) *server {
return &server{
host: options.Host,
port: options.Port,
timeout: options.Timeout,
}
}
func (s *server) Run() {
fmt.Printf("server listening on %s:%d\n", s.host, s.port)
}