-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.go
49 lines (43 loc) · 1018 Bytes
/
web.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
package main
import (
"fmt"
"net/http"
"time"
)
type WebService struct {
server *http.Server
serverMux *http.ServeMux
termination bool
}
func NewWebService() *WebService {
return &WebService{serverMux: http.NewServeMux()}
}
func (this *WebService) ListenAndServe(addr string) {
this.termination = false
for !this.termination {
fmt.Printf("[web] start listen %s\n", addr)
this.server = &http.Server{Addr: addr, Handler: this.serverMux}
err := this.server.ListenAndServe()
if err != nil {
fmt.Errorf("[web] %v\n", err)
if this.server != nil {
this.server.Close()
this.server = nil
}
time.Sleep(5 * time.Second)
}
}
}
func (this *WebService) Close() {
this.termination = true
if this.server != nil {
this.server.Close()
this.server = nil
}
}
func (this *WebService) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
if this.serverMux == nil {
this.serverMux = http.NewServeMux()
}
this.serverMux.HandleFunc(pattern, handler)
}