-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpServer.go
More file actions
68 lines (57 loc) · 1.08 KB
/
HttpServer.go
File metadata and controls
68 lines (57 loc) · 1.08 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
package main
import (
"fmt"
"io"
"net"
"net/http"
"time"
)
func hello(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
w.WriteHeader(http.StatusCreated)
} else {
io.WriteString(w, "Hello world!")
}
}
//HTTPServer ...
type HTTPServer struct {
Port int
listener net.Listener
server *http.Server
mux *http.ServeMux
}
//NewHTTPServer ...
func NewHTTPServer(port int) *HTTPServer {
return &HTTPServer{
Port: port,
}
}
//Start ...
func (instance *HTTPServer) Start() error {
l, err := net.Listen("tcp", fmt.Sprintf(":%d", instance.Port))
mux := http.NewServeMux()
mux.HandleFunc("/", hello)
s := &http.Server{
Addr: ":8080",
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()
}
}