-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
84 lines (64 loc) · 1.43 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
package hertz
import (
"context"
"crypto/tls"
"net/url"
"strings"
"time"
"github.com/apus-run/sea-kit/log"
hertz "github.com/cloudwego/hertz/pkg/app/server"
"github.com/apus-run/gaia/middleware"
"github.com/apus-run/gaia/transport"
thttp "github.com/apus-run/gaia/transport/http"
)
var (
_ transport.Server = (*Server)(nil)
_ transport.Endpointer = (*Server)(nil)
)
type Server struct {
*hertz.Hertz
tlsConf *tls.Config
timeout time.Duration
addr string
err error
filters []thttp.FilterFunc
ms []middleware.Middleware
}
func NewServer(opts ...ServerOption) *Server {
srv := &Server{
timeout: 1 * time.Second,
}
srv.init(opts...)
return srv
}
func (s *Server) init(opts ...ServerOption) {
for _, o := range opts {
o(s)
}
s.Hertz = hertz.Default(hertz.WithHostPorts(s.addr), hertz.WithTLS(s.tlsConf))
}
func (s *Server) Endpoint() (*url.URL, error) {
addr := s.addr
prefix := "http://"
if s.tlsConf == nil {
if !strings.HasPrefix(addr, "http://") {
prefix = "http://"
}
} else {
if !strings.HasPrefix(addr, "https://") {
prefix = "https://"
}
}
addr = prefix + addr
var endpoint *url.URL
endpoint, s.err = url.Parse(addr)
return endpoint, s.err
}
func (s *Server) Start(ctx context.Context) error {
log.Infof("[hertz] server listening on: %s", s.addr)
return s.Run()
}
func (s *Server) Stop(ctx context.Context) error {
log.Info("[hertz] server stopping")
return s.Shutdown(ctx)
}