forked from vadv/gopher-lua-libs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
59 lines (52 loc) · 1.09 KB
/
api.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
// Package pprof implements golang package pprof functionality.
package pprof
import (
"context"
"net/http"
_ "net/http/pprof"
"time"
lua "github.com/yuin/gopher-lua"
)
type luaPprof struct {
addr string
stop chan bool
}
func checkPprof(L *lua.LState, n int) *luaPprof {
ud := L.CheckUserData(n)
if v, ok := ud.Value.(*luaPprof); ok {
return v
}
L.ArgError(n, "pprof_ud expected")
return nil
}
// Register(string): return (pprof_ud, err)
func Register(L *lua.LState) int {
addr := L.CheckString(1)
ud := L.NewUserData()
ud.Value = &luaPprof{addr: addr, stop: make(chan bool, 1)}
L.SetMetatable(ud, L.GetTypeMetatable(`pprof_ud`))
L.Push(ud)
return 1
}
// Enable start pprof
func Enable(L *lua.LState) int {
pp := checkPprof(L, 1)
go func() {
h := &http.Server{Addr: pp.addr}
go func() {
if err := h.ListenAndServe(); err != nil {
return
}
}()
<-pp.stop
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
h.Shutdown(ctx)
}()
return 0
}
// Disable pprof stop
func Disable(L *lua.LState) int {
pp := checkPprof(L, 1)
pp.stop <- true
return 0
}