-
Notifications
You must be signed in to change notification settings - Fork 1
/
http_server.go
57 lines (46 loc) · 999 Bytes
/
http_server.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
package helpers
import (
"context"
"fmt"
"net"
"net/http"
)
type HttpServer interface {
Start()
Shutdown()
Url() string
Port() int
}
type httpServer struct {
path string
listener net.Listener
server *http.Server
}
func (h *httpServer) Start() {
go h.server.Serve(h.listener)
}
func (h *httpServer) Shutdown() {
h.server.Shutdown(context.TODO())
}
func (h *httpServer) Url() string {
return fmt.Sprintf("http://127.0.0.1:%d%s", h.listener.Addr().(*net.TCPAddr).Port, h.path)
}
func (h *httpServer) Port() int {
return h.listener.Addr().(*net.TCPAddr).Port
}
func CreateHttpServer(path string, port int, f func(writer http.ResponseWriter, request *http.Request)) HttpServer {
listener, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", port))
if err != nil {
panic(err)
}
router := http.NewServeMux()
router.HandleFunc(path, f)
server := &http.Server{
Handler: router,
}
return &httpServer{
path: path,
listener: listener,
server: server,
}
}