-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpong.go
98 lines (80 loc) · 1.65 KB
/
httpong.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
package httpong
import (
"log"
"net"
"os"
"os/signal"
"syscall"
)
type Config struct {
Addr string
Debug bool
}
type App struct {
router Router
config Config
}
func New() App {
return App{
router: newRouter(),
config: Config{Addr: ":8080"},
}
}
func NewWithConfig(config Config) App {
return App{
router: newRouter(),
config: config,
}
}
func (a *App) Run() error {
ln, err := net.Listen("tcp", a.config.Addr)
if err != nil {
return err
}
log.Println("running in port ", a.config.Addr)
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
go func() {
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
}
go handleConnection(conn, a.router)
}
}()
<-sigCh
log.Println("server shutting down..")
return nil
}
func handleConnection(conn net.Conn, router Router) {
defer conn.Close()
req := ReadReq(conn)
route := router.FindRoute(req)
context := newContext(req, conn)
if route == nil {
context.res.ResponseString(conn, "failed to access path", 404)
return
}
log.Println(route, context)
route.Function(context)
}
func (a *App) RegisterRoute(method string, path string, fn Handler) {
route := Route{method, path, fn}
a.router.registerRoute(route)
}
func (a *App) GET(path string, fn Handler) {
a.RegisterRoute("GET", path, fn)
}
func (a App) POST(path string, fn Handler) {
a.RegisterRoute("POST", path, fn)
}
func (a App) PUT(path string, fn Handler) {
a.RegisterRoute("PUT", path, fn)
}
func (a App) DELETE(path string, fn Handler) {
a.RegisterRoute("DELETE", path, fn)
}
func (a App) PATCH(path string, fn Handler) {
a.RegisterRoute("PATCH", path, fn)
}