-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhyper.go
260 lines (210 loc) · 5.86 KB
/
hyper.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
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
package hyper
import (
"bufio"
"fmt"
"log"
"net"
"regexp"
"runtime"
"strconv"
"strings"
"github.com/VarthanV/hyper/pkg/runtimeutils"
)
type hyper struct {
routes map[HttpMethod]map[string]routeStruct
staticPath string
templatesPath string
}
func New() *hyper {
return &hyper{
routes: make(map[HttpMethod]map[string]routeStruct),
staticPath: "",
templatesPath: "./templates",
}
}
func (h *hyper) ListenAndServe(host, port, startupMessage string) {
var (
startupMessageChan = make(chan string, 1)
)
printStartupMessage := func() {
for msg := range startupMessageChan {
log.Println(msg)
}
}
// Print the routes:handler mapping
for method, routes := range h.routes {
for _, f := range routes {
fmt.Printf("%s %s ----------------------> %s\n", method, f.UserGivenPath, runtimeutils.GetFunctionName(f.Handler))
}
}
go printStartupMessage()
l, err := net.Listen("tcp", fmt.Sprintf("%s:%s", host, port))
if err != nil {
log.Fatal("error in listening ", err)
}
defer l.Close()
log.Printf("Listening on %s:%s\n", host, port)
log.Printf("Templates directory configured to %s \n", h.templatesPath)
startupMessageChan <- startupMessage
close(startupMessageChan)
for {
conn, err := l.Accept()
if err != nil {
log.Println("unable to accept connection ", err)
continue
}
h.handleConnection(conn)
}
}
func (h *hyper) mapHandlers(path string, method HttpMethod, handler HandlerFunc) {
if _, ok := h.routes[method]; !ok {
h.routes[method] = make(map[string]routeStruct)
}
compliledPath := path
if !strings.HasPrefix(path, "^") {
compliledPath = fmt.Sprintf(`^%s$`, path)
}
h.routes[method][compliledPath] = routeStruct{UserGivenPath: path, Handler: handler}
}
func (h *hyper) POST(path string, handler HandlerFunc) {
h.mapHandlers(path, HttpMethodPost, handler)
}
func (h *hyper) PUT(path string, handler HandlerFunc) {
h.mapHandlers(path, HttpMethodPut, handler)
}
func (h *hyper) PATCH(path string, handler HandlerFunc) {
h.mapHandlers(path, HttpMethodPatch, handler)
}
func (h *hyper) GET(path string, handler HandlerFunc) {
h.mapHandlers(path, HttpMethodGet, handler)
}
func (h *hyper) DELETE(path string, handler HandlerFunc) {
h.mapHandlers(path, HttpMethodPatch, handler)
}
func (h *hyper) OPTIONS(path string, handler HandlerFunc) {
h.mapHandlers(path, HttpMethodOptions, handler)
}
func (h *hyper) CONNECT(path string, handler HandlerFunc) {
h.mapHandlers(path, HttpMethodConnect, handler)
}
func (h *hyper) TRACE(path string, handler HandlerFunc) {
h.mapHandlers(path, HttpMethodTrace, handler)
}
func (h *hyper) handleConnection(c net.Conn) {
var (
maxConnectionCanHandleConcurrently = runtime.NumCPU() * 10 // 10 times the magnitude of num cpu
sem = make(chan struct{}, maxConnectionCanHandleConcurrently)
)
handleConn := func(c net.Conn) {
defer c.Close()
// Put in semaphore that we are handling the connection
sem <- struct{}{}
fmt.Println("Connection from ", c.RemoteAddr().String())
// Release the sem
<-sem
w := newResponseWriter(h.templatesPath)
request, err := h.parseRequest(c)
if err != nil {
log.Println("error in parsing request ", err)
return
}
if request != nil {
handlerMap, ok := h.routes[request.Method]
if !ok {
log.Println("handler not found for method")
return
}
isHandlerMatched := false
for path, r := range handlerMap {
compiledPath := regexp.MustCompile(path)
isHandlerMatched = compiledPath.MatchString(request.Path)
if isHandlerMatched {
// Check if it matches the /:x param
re := regexp.MustCompile(`^/([^/]+)$`)
match := re.FindStringSubmatch(path)
if match != nil {
log.Println("match found with id ", 1)
}
r.Handler(w, request)
}
}
}
_, err = c.Write([]byte(w.ToRaw()))
if err != nil {
log.Println("unable to write to conn ", err)
}
log.Printf("%s %s %d", request.Method, request.Path, w.StatusCode())
}
go handleConn(c)
}
// parseRequest: Reads the raw http request and parses it into “Request“ struct
func (h *hyper) parseRequest(conn net.Conn) (*Request, error) {
request := &Request{
RemoteHostAddr: conn.RemoteAddr(),
}
reader := bufio.NewReader(conn)
// Parse the equest line (e.g., "GET /path HTTP/1.1")
requestLine, err := reader.ReadString(delimNewLine)
if err != nil {
return nil, err
}
// Split into parts
parts := strings.Split(requestLine, " ")
if len(parts) < 3 {
log.Println(ErrInvalidRequestLine.Error())
return nil, ErrInvalidRequestLine
}
request.Method = HttpMethod(parts[0])
request.Path = parts[1]
request.Protocol = parts[2]
request.headers = make(map[string]string)
queryParams := make(map[string]string)
if idx := strings.Index(request.Path, "?"); idx != -1 {
queryString := request.Path[idx+1:]
request.Path = request.Path[:idx]
queryPairs := strings.Split(queryString, "&")
for _, pair := range queryPairs {
kv := strings.SplitN(pair, "=", 2)
if len(kv) == 2 {
key := kv[0]
value := kv[1]
queryParams[key] = value
}
}
}
request.queryParams = queryParams
// Populate headers
for {
line, err := reader.ReadString(delimNewLine)
if err != nil {
fmt.Println("Error reading header:", err)
return nil, err
}
line = strings.TrimSpace(line)
// Break if we reach an empty line (end of headers)
if line == "" {
break
}
colonIndex := strings.Index(line, ":")
if colonIndex == -1 {
continue
}
key := strings.TrimSpace(line[:colonIndex])
value := strings.TrimSpace(line[colonIndex+1:])
request.headers[key] = value
}
// If there’s a Content-Length header, read the body
if l, ok := request.headers["Content-Length"]; ok {
lint, err := strconv.Atoi(l)
if err != nil {
return nil, err
}
body := make([]byte, lint)
_, err = reader.Read(body)
if err != nil {
return nil, err
}
request.Body = body
}
return request, nil
}