-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathmain.go
178 lines (161 loc) · 4.41 KB
/
main.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
174
175
176
177
178
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/naughtygopher/webgo/v7"
"github.com/naughtygopher/webgo/v7/extensions/sse"
"github.com/naughtygopher/webgo/v7/middleware/accesslog"
"github.com/naughtygopher/webgo/v7/middleware/cors"
)
var (
lastModified = time.Now().Format(http.TimeFormat)
)
func chain(w http.ResponseWriter, r *http.Request) {
r.Header.Set("chained", "true")
}
// errLogger is a middleware which will log all errors returned/set by a handler
func errLogger(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
next(w, r)
err := webgo.GetError(r)
if err != nil {
// log only server errors
if webgo.ResponseStatus(w) > 499 {
log.Println("errorLogger:", err.Error())
}
}
}
func routegroupMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
w.Header().Add("routegroup", "true")
next(w, r)
}
func getRoutes(sse *sse.SSE) []*webgo.Route {
return []*webgo.Route{
{
Name: "root",
Method: http.MethodGet,
Pattern: "/",
Handlers: []http.HandlerFunc{HomeHandler},
TrailingSlash: true,
},
{
Name: "matchall",
Method: http.MethodGet,
Pattern: "/matchall/:wildcard*",
Handlers: []http.HandlerFunc{ParamHandler},
TrailingSlash: true,
},
{
Name: "api",
Method: http.MethodGet,
Pattern: "/api/:param",
Handlers: []http.HandlerFunc{chain, ParamHandler},
TrailingSlash: true,
FallThroughPostResponse: true,
},
{
Name: "invalidjson",
Method: http.MethodGet,
Pattern: "/invalidjson",
Handlers: []http.HandlerFunc{InvalidJSONHandler},
TrailingSlash: true,
},
{
Name: "error-setter",
Method: http.MethodGet,
Pattern: "/error-setter",
Handlers: []http.HandlerFunc{ErrorSetterHandler},
TrailingSlash: true,
},
{
Name: "original-responsewriter",
Method: http.MethodGet,
Pattern: "/original-responsewriter",
Handlers: []http.HandlerFunc{OriginalResponseWriterHandler},
TrailingSlash: true,
},
{
Name: "static",
Method: http.MethodGet,
Pattern: "/static/:w*",
Handlers: []http.HandlerFunc{StaticFilesHandler},
TrailingSlash: true,
},
{
Name: "sse",
Method: http.MethodGet,
Pattern: "/sse/:clientID",
Handlers: []http.HandlerFunc{SSEHandler(sse)},
TrailingSlash: true,
},
}
}
func setup() (*webgo.Router, *sse.SSE) {
port := strings.TrimSpace(os.Getenv("HTTP_PORT"))
if port == "" {
port = "8080"
}
cfg := &webgo.Config{
Host: "",
Port: port,
HTTPSPort: "9595",
ReadTimeout: 15 * time.Second,
WriteTimeout: 1 * time.Hour,
CertFile: "./certs/localhost.crt",
KeyFile: "./certs/localhost.decrypted.key",
}
webgo.GlobalLoggerConfig(
nil, nil,
webgo.LogCfgDisableDebug,
)
routeGroup := webgo.NewRouteGroup("/v7.0.0", false)
routeGroup.Add(webgo.Route{
Name: "router-group-prefix-v7.0.0_api",
Method: http.MethodGet,
Pattern: "/api/:param",
Handlers: []http.HandlerFunc{chain, ParamHandler},
})
routeGroup.Use(routegroupMiddleware)
sseService := sse.New()
sseService.OnRemoveClient = func(ctx context.Context, clientID string, count int) {
log.Printf("\nClient %q removed, active client(s): %d\n", clientID, count)
}
sseService.OnCreateClient = func(ctx context.Context, client *sse.Client, count int) {
log.Printf("\nClient %q added, active client(s): %d\n", client.ID, count)
}
routes := getRoutes(sseService)
routes = append(routes, routeGroup.Routes()...)
router := webgo.NewRouter(cfg, routes...)
router.UseOnSpecialHandlers(accesslog.AccessLog)
router.Use(
errLogger,
cors.CORS(nil),
accesslog.AccessLog,
)
return router, sseService
}
func main() {
router, sseService := setup()
clients := []*sse.Client{}
sseService.OnCreateClient = func(ctx context.Context, client *sse.Client, count int) {
clients = append(clients, client)
}
// broadcast server time to all SSE listeners
go func() {
retry := time.Millisecond * 500
for {
now := time.Now().Format(time.RFC1123Z)
sseService.Broadcast(sse.Message{
Data: now + fmt.Sprintf(" (%d)", sseService.ActiveClients()),
Retry: retry,
})
time.Sleep(time.Second)
}
}()
go router.StartHTTPS()
router.Start()
}