-
-
Notifications
You must be signed in to change notification settings - Fork 70
/
atreugo.go
173 lines (139 loc) · 3.85 KB
/
atreugo.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package atreugo
import (
"fmt"
"net"
"os"
"os/signal"
"syscall"
"time"
"github.com/erikdubbelboer/fasthttp"
"github.com/erikdubbelboer/fasthttp/reuseport"
"github.com/savsgio/go-logger"
"github.com/thehowl/fasthttprouter"
)
// Config config for Atreugo
type Config struct {
Host string
Port int
LogLevel string
Compress bool
TLSEnable bool
CertKey string
CertFile string
GracefulEnable bool
}
// Atreugo struct for make up a server
type Atreugo struct {
server *fasthttp.Server
router *fasthttprouter.Router
middlewares []Middleware
log *logger.Logger
cfg *Config
}
// View must process incoming requests.
type View func(ctx *fasthttp.RequestCtx) error
// Middleware must process all incoming requests before defined views.
type Middleware func(ctx *fasthttp.RequestCtx) (int, error)
// New create a new instance of Atreugo Server
func New(cfg *Config) *Atreugo {
if cfg.LogLevel == "" {
cfg.LogLevel = logger.INFO
}
log := logger.New("atreugo", cfg.LogLevel, os.Stdout)
router := fasthttprouter.New()
handler := router.Handler
if cfg.Compress {
handler = fasthttp.CompressHandler(handler)
}
server := &Atreugo{
router: router,
server: &fasthttp.Server{
Handler: handler,
Name: "AtreugoFastHTTPServer",
ReadTimeout: 25 * time.Second,
},
log: log,
cfg: cfg,
}
return server
}
func (s *Atreugo) viewHandler(viewFn View) fasthttp.RequestHandler {
return fasthttp.RequestHandler(func(ctx *fasthttp.RequestCtx) {
s.log.Debugf("%s %s", ctx.Method(), ctx.URI())
for _, middlewareFn := range s.middlewares {
if statusCode, err := middlewareFn(ctx); err != nil {
s.log.Errorf("Msg: %v | RequestUri: %s", err, ctx.URI().String())
JsonResponse(ctx, Json{"Error": err.Error()}, statusCode)
return
}
}
if err := viewFn(ctx); err != nil {
s.log.Error(err)
}
})
}
func (s *Atreugo) getListener(addr string) net.Listener {
network := "tcp4"
ln, err := reuseport.Listen(network, addr)
if err == nil {
return ln
}
s.log.Errorf("Error in reuseport listener %s", err)
s.log.Infof("Trying with net listener")
ln, err = net.Listen(network, addr)
if err != nil {
s.log.Fatalf("Error in net listener %s", err)
}
return ln
}
func (s *Atreugo) serve(ln net.Listener, protocol, addr string) error {
s.log.Infof("Listening on: %s://%s/", protocol, addr)
if s.cfg.TLSEnable {
return s.server.ServeTLS(ln, s.cfg.CertFile, s.cfg.CertKey)
}
return s.server.Serve(ln)
}
func (s *Atreugo) serveGracefully(ln net.Listener, protocol, addr string) error {
listenErr := make(chan error, 1)
go func() {
listenErr <- s.serve(ln, protocol, addr)
}()
osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, syscall.SIGINT, syscall.SIGTERM)
select {
case err := <-listenErr:
return err
case <-osSignals:
s.log.Infof("Shutdown signal received")
if err := s.server.Shutdown(); err != nil {
return err
}
s.log.Infof("Server gracefully stopped")
}
return nil
}
// Static add view for static files
func (s *Atreugo) Static(rootStaticDirPath string) {
s.router.NotFound = fasthttp.FSHandler(rootStaticDirPath, 0)
}
// Path add the views to serve
func (s *Atreugo) Path(httpMethod string, url string, viewFn View) {
callFuncByName(s.router, httpMethod, url, s.viewHandler(viewFn))
}
// UseMiddleware register middleware functions that viewHandler will use
func (s *Atreugo) UseMiddleware(fns ...Middleware) {
s.middlewares = append(s.middlewares, fns...)
}
// ListenAndServe start Atreugo server according to the configuration
func (s *Atreugo) ListenAndServe() error {
protocol := "http"
if s.cfg.TLSEnable {
protocol = "https"
}
addr := fmt.Sprintf("%s:%d", s.cfg.Host, s.cfg.Port)
ln := s.getListener(addr)
if s.cfg.GracefulEnable {
return s.serveGracefully(ln, protocol, addr)
}
return s.serve(ln, protocol, addr)
}