This repository has been archived by the owner on Jul 6, 2023. It is now read-only.
/
server.go
126 lines (108 loc) · 2.31 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
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 servers
import (
"context"
"fmt"
"net/http"
"net/url"
etcd "go.etcd.io/etcd/client/v3"
"github.com/anqur/gbio/core/internal/endpoints"
"github.com/anqur/gbio/core/internal/registries"
"github.com/anqur/gbio/core/internal/utils"
"github.com/anqur/gbio/core/logging"
)
type Server struct {
u *url.URL
m *http.ServeMux
s http.Server
eps map[string]*Endpoint
reg *registries.Registry
}
type Option func(s *Server)
func New(rawURL string, opts ...Option) (*Server, error) {
u, err := url.Parse(rawURL)
if err != nil {
return nil, err
}
m := new(http.ServeMux)
s := &Server{
u: u,
m: m,
s: http.Server{
Addr: u.Host,
Handler: m,
},
eps: make(map[string]*Endpoint),
}
for _, opt := range opts {
opt(s)
}
return s, nil
}
func Use(opts ...Option) *Server {
for _, opt := range opts {
opt(Default)
}
return Default
}
var Default, _ = New("http://0.0.0.0:8080")
func WithRegistry(
cfg *etcd.Config,
opts ...RegistryOption,
) Option {
return func(s *Server) {
s.reg = registries.New(cfg)
for _, opt := range opts {
opt(s.reg)
}
}
}
func ListenAndServe() error { return Default.ListenAndServe() }
func (s *Server) ListenAndServe() error {
for _, srv := range s.eps {
logging.Info.Println("Registering:", srv.Name, srv.BaseURI)
s.m.HandleFunc(srv.BaseURI, srv.Handler)
}
if s.reg != nil {
if err := s.registerServer(); err != nil {
return err
}
}
logging.Info.Println("Listening:", s.s.Addr)
return s.s.ListenAndServe()
}
func (s *Server) Register(srv *Endpoint) {
s.eps[srv.Name] = srv
}
func (s *Server) serverAddr() (string, error) {
ip, err := utils.GetIPv4()
if err != nil {
return "", err
}
port := s.u.Port()
if port == "" {
return ip, nil
}
return fmt.Sprintf("%s:%s", ip, port), nil
}
func (s *Server) registerServer() error {
addr, err := s.serverAddr()
if err != nil {
return nil
}
var eps []*endpoints.Endpoint
for _, ep := range s.eps {
eps = append(eps, &ep.Endpoint)
}
return s.reg.Register(addr, eps)
}
type Endpoint struct {
endpoints.Endpoint
Handler http.HandlerFunc
}
type RegistryOption func(r *registries.Registry)
func WithContext(ctx context.Context) RegistryOption {
return func(r *registries.Registry) { r.Ctx = ctx }
}
func WithPrefix(p string) RegistryOption {
return func(r *registries.Registry) { r.Prefix = p }
}