-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
96 lines (68 loc) · 2.01 KB
/
server.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
90
91
92
93
94
95
96
package server
import (
"context"
"fmt"
_ "log"
"net/http"
"net/url"
"sort"
"github.com/aaronland/go-roster"
)
// type Server is an interface for creating server instances that serve requests using a `http.Handler` router.
type Server interface {
// ListenAndServe starts the server and listens for requests using a `http.Handler` instance for routing.
ListenAndServe(context.Context, http.Handler) error
// Address returns the fully-qualified URI that the server is listening for requests on.
Address() string
}
// ServeritializeFunc is a function used to initialize an implementation of the `Server` interface.
type ServerInitializeFunc func(context.Context, string) (Server, error)
var servers roster.Roster
func ensureServers() error {
if servers == nil {
r, err := roster.NewDefaultRoster()
if err != nil {
return err
}
servers = r
}
return nil
}
// RegisterServer() associates 'scheme' with 'f' in an internal list of avilable `Server` implementations.
func RegisterServer(ctx context.Context, scheme string, f ServerInitializeFunc) error {
err := ensureServers()
if err != nil {
return err
}
return servers.Register(ctx, scheme, f)
}
// NewServer() returns a new instance of `Server` for the scheme associated with 'uri'. It is assumed that this scheme
// will have previously been "registered" with the `RegisterServer` method.
func NewServer(ctx context.Context, uri string) (Server, error) {
err := ensureServers()
if err != nil {
return nil, err
}
u, err := url.Parse(uri)
if err != nil {
return nil, err
}
scheme := u.Scheme
i, err := servers.Driver(ctx, scheme)
if err != nil {
return nil, err
}
f := i.(ServerInitializeFunc)
return f(ctx, uri)
}
// Schemes() returns the list of schemes that have been "registered".
func Schemes() []string {
ctx := context.Background()
drivers := servers.Drivers(ctx)
schemes := make([]string, len(drivers))
for idx, dr := range drivers {
schemes[idx] = fmt.Sprintf("%s://", dr)
}
sort.Strings(schemes)
return schemes
}