-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
91 lines (76 loc) · 2.18 KB
/
main.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
package main
import (
"log"
"net/http"
"os"
"runtime/debug"
"strconv"
"github.com/arl/statsviz"
example "github.com/arl/statsviz/_example"
"github.com/docker/go-units"
"github.com/gin-gonic/gin"
)
type configJson struct {
GOMEMLIMIT string `json:"gomemlimit"` // in human bytes
GOGC string `json:"gogc"` // in integer percentage
}
func main() {
r := SetUpRouter(true)
r.Run(":8080")
}
func SetUpRouter(withRoutes bool) *gin.Engine {
// Force the GC to work to make the plots "move".
go example.Work()
r := gin.New()
if withRoutes {
r.GET("/config", readConfigHandler)
r.POST("/config", updateConfigHandler)
r.GET("/debug/statsviz/*filepath", statsvizHandler)
}
return r
}
func getConfigJson() configJson {
var configJson configJson
configJson.GOMEMLIMIT = os.Getenv("GOMEMLIMIT")
configJson.GOGC = os.Getenv("GOGC")
return configJson
}
func readConfigHandler(c *gin.Context) {
currentConfig := getConfigJson()
log.Printf("current config: %+v", currentConfig)
c.IndentedJSON(http.StatusOK, currentConfig)
}
func updateConfigHandler(c *gin.Context) {
var req *configJson
if err := c.BindJSON(&req); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
log.Printf("requested config: %+v", req)
requestedMemoryLimit, _ := units.FromHumanSize(req.GOMEMLIMIT)
if requestedMemoryLimit > 0 {
debug.SetMemoryLimit(requestedMemoryLimit)
log.Printf("memory limit set to %d bytes", requestedMemoryLimit)
os.Setenv("GOMEMLIMIT", req.GOMEMLIMIT)
}
requestedGOGC, _ := strconv.Atoi(req.GOGC)
if requestedGOGC > 0 {
debug.SetGCPercent(requestedGOGC)
log.Printf("GOGC set to %d percent", requestedGOGC)
os.Setenv("GOGC", req.GOGC)
} else if req.GOGC == "off" {
debug.SetGCPercent(-1)
log.Printf("GOGC limit set to off")
os.Setenv("GOGC", req.GOGC)
}
updated := getConfigJson()
log.Printf("updated config: %+v", updated)
c.IndentedJSON(http.StatusOK, req)
}
func statsvizHandler(c *gin.Context) {
if c.Param("filepath") == "/ws" {
statsviz.Ws(c.Writer, c.Request)
return
}
statsviz.IndexAtRoot("/debug/statsviz").ServeHTTP(c.Writer, c.Request)
}