github.com/zhongdalu/gf@v1.0.0/g/net/ghttp/ghttp_server_admin.go (about)

     1  // Copyright 2018 gf Author(https://github.com/zhongdalu/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/zhongdalu/gf.
     6  // pprof封装.
     7  
     8  package ghttp
     9  
    10  import (
    11  	"github.com/zhongdalu/gf/g/os/gproc"
    12  	"github.com/zhongdalu/gf/g/os/gtimer"
    13  	"github.com/zhongdalu/gf/g/os/gview"
    14  	"os"
    15  	"strings"
    16  	"time"
    17  )
    18  
    19  // 服务管理首页
    20  func (p *utilAdmin) Index(r *Request) {
    21  	data := map[string]interface{}{
    22  		"pid": gproc.Pid(),
    23  		"uri": strings.TrimRight(r.URL.Path, "/"),
    24  	}
    25  	buffer, _ := gview.ParseContent(`
    26              <html>
    27              <head>
    28                  <title>GoFrame Web Server Admin</title>
    29              </head>
    30              <body>
    31                  <p>PID: {{.pid}}</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  
    40  // 服务重启
    41  func (p *utilAdmin) Restart(r *Request) {
    42  	var err error = nil
    43  	// 必须检查可执行文件的权限
    44  	path := r.GetQueryString("newExeFilePath")
    45  	if path == "" {
    46  		path = os.Args[0]
    47  	}
    48  	// 执行重启操作
    49  	if len(path) > 0 {
    50  		err = RestartAllServer(path)
    51  	} else {
    52  		err = RestartAllServer()
    53  	}
    54  	if err == nil {
    55  		r.Response.Write("server restarted")
    56  	} else {
    57  		r.Response.Write(err.Error())
    58  	}
    59  }
    60  
    61  // 服务关闭
    62  func (p *utilAdmin) Shutdown(r *Request) {
    63  	r.Server.Shutdown()
    64  	if err := ShutdownAllServer(); err == nil {
    65  		r.Response.Write("server shutdown")
    66  	} else {
    67  		r.Response.Write(err.Error())
    68  	}
    69  }
    70  
    71  // 开启服务管理支持
    72  func (s *Server) EnableAdmin(pattern ...string) {
    73  	p := "/debug/admin"
    74  	if len(pattern) > 0 {
    75  		p = pattern[0]
    76  	}
    77  	s.BindObject(p, &utilAdmin{})
    78  }
    79  
    80  // 关闭当前Web Server
    81  func (s *Server) Shutdown() error {
    82  	// 非终端信号下,异步1秒后再执行关闭,
    83  	// 目的是让接口能够正确返回结果,否则接口会报错(因为web server关闭了)
    84  	gtimer.SetTimeout(time.Second, func() {
    85  		// 只关闭当前的Web Server
    86  		for _, v := range s.servers {
    87  			v.close()
    88  		}
    89  	})
    90  	return nil
    91  }