/
server.go
106 lines (86 loc) · 2.04 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
package web
import (
"codnect.io/procyon/web/http"
"codnect.io/procyon/web/http/router"
"context"
"errors"
"fmt"
stdhttp "net/http"
"sync"
)
type Server interface {
Start() error
Stop() error
Port() int
ShutDownGracefully(ctx context.Context) error
}
type ServerProperties struct {
//property.Properties `prefix:"server"`
Port int `prop:"port" default:"8080"`
}
type DefaultServer struct {
props ServerProperties
server *stdhttp.Server
contextPool sync.Pool
mappingRegistry *router.MappingRegistry
errorHandler http.ErrorHandler
}
func NewDefaultServer() *DefaultServer {
return &DefaultServer{
contextPool: sync.Pool{
New: func() any {
return newServerContext()
},
},
}
}
func (s *DefaultServer) Start() error {
s.server = &stdhttp.Server{
Addr: fmt.Sprintf(":%d", s.props.Port),
Handler: s,
}
return nil
}
func (s *DefaultServer) Stop() error {
return s.server.Shutdown(context.Background())
}
func (s *DefaultServer) Port() int {
return s.props.Port
}
func (s *DefaultServer) ShutDownGracefully(ctx context.Context) error {
if err := s.server.Shutdown(ctx); err != nil {
return err
}
return nil
}
func (s *DefaultServer) ServeHTTP(writer stdhttp.ResponseWriter, request *stdhttp.Request) {
ctx := s.contextPool.Get().(*ServerContext)
ctx.Reset(request, writer)
defer func() {
if runtimeError := recover(); runtimeError != nil {
s.handlerRuntimeError(ctx, runtimeError)
s.contextPool.Put(ctx)
}
}()
chain, exists := s.mappingRegistry.GetHandler(ctx)
if exists {
ctx.HandlerChain = chain
ctx.Invoke(ctx)
if ctx.Err() != nil {
s.errorHandler.HandleError(ctx, ctx.Err())
}
} else {
s.errorHandler.HandleError(ctx, &http.NotFoundError{})
}
s.contextPool.Put(ctx)
}
func (s *DefaultServer) handlerRuntimeError(ctx http.Context, runtimeError any) {
switch err := runtimeError.(type) {
case error:
s.errorHandler.HandleError(ctx, err)
case string:
s.errorHandler.HandleError(ctx, errors.New(err))
default:
s.errorHandler.HandleError(ctx, fmt.Errorf("unknown error: %v", err))
}
}