/
ghttp_server_admin.go
97 lines (88 loc) · 2.5 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
// Copyright 2018 gf Author(https://github.com/gogf/gf). 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 (
"os"
"strings"
"time"
"github.com/gogf/gf/os/gproc"
"github.com/gogf/gf/os/gtimer"
"github.com/gogf/gf/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(),
"uri": strings.TrimRight(r.URL.Path, "/"),
}
buffer, _ := gview.ParseContent(`
<html>
<head>
<title>GoFrame Web Server Admin</title>
</head>
<body>
<p>PID: {{.pid}}</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 err error = nil
// Custom start binary path when this process exits.
path := r.GetQueryString("newExeFilePath")
if path == "" {
path = os.Args[0]
}
if len(path) > 0 {
err = RestartAllServer(path)
} else {
err = RestartAllServer()
}
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) {
if err := r.Server.Shutdown(); err != nil {
r.Response.WriteExit(err.Error())
}
if err := ShutdownAllServer(); err == nil {
r.Response.WriteExit("server shutdown")
} else {
r.Response.WriteExit(err.Error())
}
}
// 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 {
// It shuts down the server after 1 second, which is not triggered by system signal,
// to ensure the response successfully to the client.
gtimer.SetTimeout(time.Second, func() {
// Only shut down current server.
// It may have multiple underlying http servers.
for _, v := range s.servers {
v.close()
}
})
return nil
}