-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
220 lines (185 loc) · 5.17 KB
/
Copy pathapp.go
File metadata and controls
220 lines (185 loc) · 5.17 KB
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package zttp
import (
"bufio"
"crypto/tls"
"fmt"
"log"
"net"
"strings"
"time"
)
type App struct {
*Router
Routers []*Router
PrettyPrintJSON bool
}
type Ctx struct {
Req *Req
Res *Res
}
// New App constructor
func NewApp() *App {
defaultRouter := &Router{
getRoutes: []Route{},
postRoutes: []Route{},
deleteRoutes: []Route{},
putRoutes: []Route{},
patchRoutes: []Route{},
middlewares: []MiddlewareWrapper{},
}
app := &App{
Router: defaultRouter,
Routers: []*Router{defaultRouter},
}
defaultRouter.App = app
return app
}
// New Router constructor
func (app *App) NewRouter(path string) *Router {
router := &Router{
App: app,
prefix: path,
getRoutes: []Route{},
postRoutes: []Route{},
deleteRoutes: []Route{},
putRoutes: []Route{},
patchRoutes: []Route{},
middlewares: []MiddlewareWrapper{},
}
app.Routers = append(app.Routers, router)
return router
}
// Start listening to the given port
func (app *App) Start(port int) {
// Initiate the tcp server sockets
server, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
log.Fatalf("err initiating server... %s", err.Error())
}
defer server.Close()
for {
// accept tcp socket connections indefinitely
socket, err := server.Accept()
if err != nil {
log.Println("err accepting socket: ", err)
continue
}
// handle the connected client tcp socket in a goroutine
go handleClient(socket, app)
}
}
// Start listening securely to the given port
func (app *App) StartTls(port int, certFile, keyFile string) {
// Load TLS certificate and key files
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
log.Fatalf("failed to load key pair: %s", err)
}
// Pass them to the TLS config
config := &tls.Config{Certificates: []tls.Certificate{cert}}
// Initiate the tcp server sockets securely
server, err := tls.Listen("tcp", fmt.Sprintf(":%d", port), config)
if err != nil {
log.Fatalf("failed to start TLS listener: %s", err)
}
defer server.Close()
for {
// accept tcp socket connections indefinitely
socket, err := server.Accept()
if err != nil {
log.Println("err accepting TLS connection:", err)
continue
}
// handle the connected client tcp socket in a goroutine
go handleClient(socket, app)
}
}
// The Front Controller
// This function is responsible for handling the incoming request from the client tcp socket
// from the beginning until it sends a response and close the connection eventually
func handleClient(socket net.Conn, app *App) {
defer func() {
if r := recover(); r != nil {
log.Printf("Recovered from panic: %v", r)
sendResponse(socket, []byte("Internal Server Error"), 500, "text/plain", nil)
}
socket.Close()
}()
// Buffer reader to read from the client tcp socket
rdr := bufio.NewReader(socket)
for {
// Set hard-coded read timeout for now
// TODO: Make it an app's config specification later
if err := socket.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
log.Printf("Error setting read deadline: %v", err)
return
}
// Extract the request line, headers, and body
requestParts := extractRequestLine(rdr, socket)
// TODO: make extractRequestLine() return []string, bool instead
// NOTE: THIS WAS ADDED TO AVOID EMPTY TCP CONNECTIONS MADE BY POSTMAN
// I think this is somehow related to the keep-alive request header
// I will figure it out later
if len(requestParts) < 2 {
// Request was already handled and response sent, so just return
return
}
headers, contentLength := extractHeaders(rdr)
body := extractBody(rdr, contentLength)
cookies := extractCookies(headers)
// Extract the method and the raw path from the request line
method := requestParts[0]
rawPath := requestParts[1]
path := rawPath
queries := make(map[string]string)
// Extract the local address carefully
// TODO: Separate and generate unit tests later
hostName := ""
addr := socket.LocalAddr()
if addr != nil {
hostName = addr.String()
}
// Extract queries, if exist
if strings.Contains(rawPath, "?") {
split := strings.SplitN(rawPath, "?", 2)
path = split[0]
queries = extractQueries(split[1])
}
// Find the matched handler from the router with parsing params, if exist
handler, params := findHandler(method, path, socket, app)
// If a handler matched, call it with the generated request and response objects
// Otherwise, send a 404 not found response
if handler != nil {
req := &Req{
LocalAddress: hostName,
Method: method,
Path: path,
Body: body,
Headers: headers,
Params: params,
Queries: queries,
Cookies: cookies,
}
res := &Res{
Socket: socket,
StatusCode: 200,
Headers: make(map[string][]string),
PrettyPrintJSON: app.PrettyPrintJSON,
}
ctx := &Ctx{
Req: req,
Res: res,
}
req.Ctx = ctx
res.Ctx = ctx
handler(req, res)
} else {
sendResponse(socket, []byte("Not Found"), 404, "text/plain", nil)
}
// Check if client requested connection close
connectionHeader := strings.ToLower(headers["Connection"])
if connectionHeader == "close" {
return
}
}
}