-
Notifications
You must be signed in to change notification settings - Fork 0
/
HttpServer.go
76 lines (65 loc) · 1.41 KB
/
HttpServer.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
package rizo
import (
"fmt"
"net"
"net/http"
"time"
)
//HTTPServer ...
type HTTPServer struct {
Port uint
listener net.Listener
server *http.Server
mux *http.ServeMux
paths map[string]*PathHandler
}
//NewHTTPServer ...
func NewHTTPServer(port uint) *HTTPServer {
return &HTTPServer{
Port: port,
paths: map[string]*PathHandler{},
}
}
//Start ...
func (instance *HTTPServer) Start() error {
l, err := net.Listen("tcp", fmt.Sprintf(":%d", instance.Port))
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if _, ok := instance.paths[r.URL.Path]; !ok {
w.WriteHeader(http.StatusNotFound)
} else {
instance.paths[r.URL.Path].Handle(w, r)
}
})
s := &http.Server{
Addr: fmt.Sprintf(":%d", instance.Port),
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
if err != nil {
return err
}
instance.listener = l
instance.mux = mux
instance.server = s
go func(listener net.Listener) {
s.Serve(listener)
}(l)
return nil
}
//Stop ...
func (instance *HTTPServer) Stop() {
if instance.listener != nil {
instance.listener.Close()
}
time.Sleep(1)
}
//Get ...
func (instance *HTTPServer) Get(path string, handler http.HandlerFunc) {
if _, ok := instance.paths[path]; !ok {
instance.paths[path] = NewPathHandler()
}
instance.paths[path].Get(handler)
}