ghttp_server_admin.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright GoFrame Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package ghttp
  7. import (
  8. "github.com/gogf/gf/os/gfile"
  9. "strings"
  10. "time"
  11. "github.com/gogf/gf/os/gproc"
  12. "github.com/gogf/gf/os/gtimer"
  13. "github.com/gogf/gf/os/gview"
  14. )
  15. // utilAdmin is the controller for administration.
  16. type utilAdmin struct{}
  17. // Index shows the administration page.
  18. func (p *utilAdmin) Index(r *Request) {
  19. data := map[string]interface{}{
  20. "pid": gproc.Pid(),
  21. "path": gfile.SelfPath(),
  22. "uri": strings.TrimRight(r.URL.Path, "/"),
  23. }
  24. buffer, _ := gview.ParseContent(`
  25. <html>
  26. <head>
  27. <title>GoFrame Web Server Admin</title>
  28. </head>
  29. <body>
  30. <p>Pid: {{.pid}}</p>
  31. <p>File Path: {{.path}}</p>
  32. <p><a href="{{$.uri}}/restart">Restart</a></p>
  33. <p><a href="{{$.uri}}/shutdown">Shutdown</a></p>
  34. </body>
  35. </html>
  36. `, data)
  37. r.Response.Write(buffer)
  38. }
  39. // Restart restarts all the servers in the process.
  40. func (p *utilAdmin) Restart(r *Request) {
  41. var err error = nil
  42. // Custom start binary path when this process exits.
  43. path := r.GetQueryString("newExeFilePath")
  44. if path == "" {
  45. path = gfile.SelfPath()
  46. }
  47. if len(path) > 0 {
  48. err = RestartAllServer(path)
  49. } else {
  50. err = RestartAllServer()
  51. }
  52. if err == nil {
  53. r.Response.WriteExit("server restarted")
  54. } else {
  55. r.Response.WriteExit(err.Error())
  56. }
  57. }
  58. // Shutdown shuts down all the servers.
  59. func (p *utilAdmin) Shutdown(r *Request) {
  60. gtimer.SetTimeout(time.Second, func() {
  61. // It shuts down the server after 1 second, which is not triggered by system signal,
  62. // to ensure the response successfully to the client.
  63. _ = r.Server.Shutdown()
  64. })
  65. r.Response.WriteExit("server shutdown")
  66. }
  67. // EnableAdmin enables the administration feature for the process.
  68. // The optional parameter <pattern> specifies the URI for the administration page.
  69. func (s *Server) EnableAdmin(pattern ...string) {
  70. p := "/debug/admin"
  71. if len(pattern) > 0 {
  72. p = pattern[0]
  73. }
  74. s.BindObject(p, &utilAdmin{})
  75. }
  76. // Shutdown shuts down current server.
  77. func (s *Server) Shutdown() error {
  78. // Only shut down current servers.
  79. // It may have multiple underlying http servers.
  80. for _, v := range s.servers {
  81. v.close()
  82. }
  83. return nil
  84. }