-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
54 lines (47 loc) · 1.36 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
package httpserver
import (
"context"
"net/http"
"time"
"github.com/herb-go/herb/service/httpservice"
"github.com/herb-go/util"
)
//MustListenAndServeHTTP listen and serve http server with given server,config and handler.
//Panic if any error raised.
func MustListenAndServeHTTP(s *http.Server, config *httpservice.Config, app http.Handler) {
l, err := config.Listen()
if err != nil {
panic(err)
}
go func() {
var err error
defer l.Close()
s.Handler = app
if config.TLS {
util.Println("Listening https " + l.Addr().String())
err = s.ServeTLS(l, config.TLSCertPath, config.TLSKeyPath)
} else {
util.Println("Listening " + l.Addr().String())
err = s.Serve(l)
}
if err != nil && err != http.ErrServerClosed {
panic(err)
}
}()
}
// ShutdownHTTP shutdown http server.
func ShutdownHTTP(Server *http.Server) {
WithContextShutdown(context.Background(), Server)
}
//ShutdownHTTPWithTimeout shutdown http server ith given timeout.
func ShutdownHTTPWithTimeout(Server *http.Server, Timeout time.Duration) {
ctx, fn := context.WithTimeout(context.Background(), Timeout)
fn()
WithContextShutdown(ctx, Server)
}
//WithContextShutdown shutdown http server ith given context.
func WithContextShutdown(ctx context.Context, Server *http.Server) {
util.Println("Http server shuting down...")
Server.Shutdown(ctx)
util.Println("Http server Stoped.")
}