/
httpserver.go
71 lines (59 loc) 路 1.62 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
package web
import (
"github.com/yoyofx/yoyogo/abstractions"
"github.com/yoyofx/yoyogo/abstractions/hostenv"
"golang.org/x/net/context"
"log"
"net/http"
)
type HttpServer struct {
IsTLS bool
Addr, CertFile, KeyFile string
webserver *http.Server
}
func DefaultHttpServer(addr string) *HttpServer {
return &HttpServer{IsTLS: false, Addr: addr}
}
func DefaultHttps(addr string, cert string, key string) *HttpServer {
return &HttpServer{IsTLS: true, Addr: addr, CertFile: cert, KeyFile: key}
}
func NewDefaultHttpByConfig(config hostenv.HttpServerConfig) *HttpServer {
if config.IsTLS {
return DefaultHttps(config.Addr, config.CertFile, config.KeyFile)
} else {
return DefaultHttpServer(config.Addr)
}
}
func (server *HttpServer) GetAddr() string {
return server.Addr
}
func (server *HttpServer) Run(context *abstractions.HostBuilderContext) (e error) {
addr := server.Addr
if server.Addr == "" {
addr = context.HostingEnvironment.Addr
}
server.webserver = &http.Server{
Addr: addr,
Handler: context.RequestDelegate.(IRequestDelegate),
}
context.ApplicationCycle.StartApplication()
if server.IsTLS {
e = server.webserver.ListenAndServeTLS(server.CertFile, server.KeyFile)
} else {
e = server.webserver.ListenAndServe()
}
if e != nil {
if e == http.ErrServerClosed {
log.Print("Server closed under request")
} else {
log.Fatal("Server closed unexpected")
}
}
return nil
}
func (server *HttpServer) Shutdown() {
if err := server.webserver.Shutdown(context.Background()); err != nil {
log.Fatal("Shutdown server:", err)
}
log.Fatal("Shutdown HTTP server...")
}