-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
58 lines (52 loc) · 1.02 KB
/
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
58
package gRouter
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
)
type HttpServer struct {
IEngine
srv *http.Server
}
func NewServer(opt *Option) *HttpServer {
engine := NewEngine(opt)
serv := &HttpServer{
IEngine: engine,
srv: &http.Server{
Addr: fmt.Sprintf(":%d", option.HttpPort),
Handler: engine,
ReadTimeout: option.ReadTimeout,
WriteTimeout: option.WriteTimeout,
},
}
return serv
}
func DefaultServer() *HttpServer {
opt := &Option{}
return NewServer(opt)
}
func (h *HttpServer) Run() {
go func() {
err := h.srv.ListenAndServe()
if err != nil {
fmt.Println("HttpServer.Start error=", err.Error())
os.Exit(1)
}
}()
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Kill, syscall.SIGTERM, syscall.SIGINT)
single := <-ch
h.Stop()
if i, ok := single.(syscall.Signal); ok {
fmt.Println("main exit ", i)
}
}
func (h *HttpServer) Stop() {
err := h.srv.Shutdown(context.Background())
if err != nil {
fmt.Println("HttpServer.Stop error=", err.Error())
}
}