/
ghttp_server_admin.go
100 lines (91 loc) · 2.57 KB
/
ghttp_server_admin.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package ghttp
import (
"context"
"strings"
"time"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gproc"
"github.com/gogf/gf/v2/os/gtimer"
"github.com/gogf/gf/v2/os/gview"
)
// utilAdmin is the controller for administration.
type utilAdmin struct{}
// Index shows the administration page.
func (p *utilAdmin) Index(r *Request) {
data := map[string]interface{}{
"pid": gproc.Pid(),
"path": gfile.SelfPath(),
"uri": strings.TrimRight(r.URL.Path, "/"),
}
buffer, _ := gview.ParseContent(r.Context(), `
<html>
<head>
<title>GoFrame Web Server Admin</title>
</head>
<body>
<p>Pid: {{.pid}}</p>
<p>File Path: {{.path}}</p>
<p><a href="{{$.uri}}/restart">Restart</a></p>
<p><a href="{{$.uri}}/shutdown">Shutdown</a></p>
</body>
</html>
`, data)
r.Response.Write(buffer)
}
// Restart restarts all the servers in the process.
func (p *utilAdmin) Restart(r *Request) {
var (
ctx = r.Context()
err error
)
// Custom start binary path when this process exits.
path := r.GetQuery("newExeFilePath").String()
if path == "" {
path = gfile.SelfPath()
}
if len(path) > 0 {
err = RestartAllServer(ctx, path)
} else {
err = RestartAllServer(ctx)
}
if err == nil {
r.Response.WriteExit("server restarted")
} else {
r.Response.WriteExit(err.Error())
}
}
// Shutdown shuts down all the servers.
func (p *utilAdmin) Shutdown(r *Request) {
gtimer.SetTimeout(r.Context(), time.Second, func(ctx context.Context) {
// It shuts down the server after 1 second, which is not triggered by system signal,
// to ensure the response successfully to the client.
_ = r.Server.Shutdown()
})
r.Response.WriteExit("server shutdown")
}
// EnableAdmin enables the administration feature for the process.
// The optional parameter `pattern` specifies the URI for the administration page.
func (s *Server) EnableAdmin(pattern ...string) {
p := "/debug/admin"
if len(pattern) > 0 {
p = pattern[0]
}
s.BindObject(p, &utilAdmin{})
}
// Shutdown shuts down current server.
func (s *Server) Shutdown() error {
var (
ctx = context.TODO()
)
// Only shut down current servers.
// It may have multiple underlying http servers.
for _, v := range s.servers {
v.close(ctx)
}
return nil
}