github.com/sagernet/sing-box@v1.2.7/cmd/sing-box/debug.go (about)

     1  //go:build debug
     2  
     3  package main
     4  
     5  import (
     6  	"encoding/json"
     7  	"net/http"
     8  	_ "net/http/pprof"
     9  	"runtime"
    10  	"runtime/debug"
    11  
    12  	"github.com/sagernet/sing-box/common/badjson"
    13  	"github.com/sagernet/sing-box/log"
    14  
    15  	"github.com/dustin/go-humanize"
    16  )
    17  
    18  func init() {
    19  	http.HandleFunc("/debug/gc", func(writer http.ResponseWriter, request *http.Request) {
    20  		writer.WriteHeader(http.StatusNoContent)
    21  		go debug.FreeOSMemory()
    22  	})
    23  	http.HandleFunc("/debug/memory", func(writer http.ResponseWriter, request *http.Request) {
    24  		var memStats runtime.MemStats
    25  		runtime.ReadMemStats(&memStats)
    26  
    27  		var memObject badjson.JSONObject
    28  		memObject.Put("heap", humanize.IBytes(memStats.HeapInuse))
    29  		memObject.Put("stack", humanize.IBytes(memStats.StackInuse))
    30  		memObject.Put("idle", humanize.IBytes(memStats.HeapIdle-memStats.HeapReleased))
    31  		memObject.Put("goroutines", runtime.NumGoroutine())
    32  		memObject.Put("rss", rusageMaxRSS())
    33  
    34  		encoder := json.NewEncoder(writer)
    35  		encoder.SetIndent("", "  ")
    36  		encoder.Encode(memObject)
    37  	})
    38  	go func() {
    39  		err := http.ListenAndServe("0.0.0.0:8964", nil)
    40  		if err != nil {
    41  			log.Debug(err)
    42  		}
    43  	}()
    44  }