Documentation ¶
Overview ¶
Package rest serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool.
The package is typically only imported for the side effect of registering its HTTP handlers. The handled paths all begin with /debug/pprof/.
To use pprof, link this package into your program:
import _ "net/http/pprof"
If your application is not already running an http server, you need to start one. Add "net/http" and "log" to your imports and the following code to your main function:
go func() { log2.Println(http.ListenAndServe("localhost:6060", nil)) }()
By default, all the profiles listed in runtime/pprof.Profile are available (via Handler), in addition to the Cmdline, Profile, Symbol, and Trace profiles defined in this package. If you are not using DefaultServeMux, you will have to register handlers with the mux you are using.
Parameters ¶
Parameters can be passed via GET query params:
- debug=N (all profiles): response format: N = 0: binary (default), N > 0: plaintext
- gc=N (heap profile): N > 0: run a garbage collection cycle before profiling
- seconds=N (allocs, block, goroutine, heap, mutex, threadcreate profiles): return a delta profile
- seconds=N (cpu (profile), trace profiles): profile for the given duration
Usage examples ¶
Use the pprof tool to look at the heap profile:
go tool pprof http://localhost:6060/debug/pprof/heap
Or to look at a 30-second CPU profile:
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
Or to look at the goroutine blocking profile, after calling runtime.SetBlockProfileRate in your program:
go tool pprof http://localhost:6060/debug/pprof/block
Or to look at the holders of contended mutexes, after calling runtime.SetMutexProfileFraction in your program:
go tool pprof http://localhost:6060/debug/pprof/mutex
The package also exports a handler that serves execution trace data for the "go tool trace" command. To collect a 5-second execution trace:
curl -o trace.out http://localhost:6060/debug/pprof/trace?seconds=5 go tool trace trace.out
To view all available profiles, open http://localhost:6060/debug/pprof/ in your browser.
For a study of the facility in action, visit https://blog.golang.org/2011/06/profiling-go-programs.html.
Index ¶
- Constants
- Variables
- func BodyMaxBytes(n int64) func(inner http.Handler) http.Handler
- func BulkHead(workers int, maxWaitTime time.Duration) func(inner http.Handler) http.Handler
- func CallbackOnChange(listener *httpConfigListener) func(event *configmgr.NacosChangeEvent)
- func Cmdline(w http.ResponseWriter, r *http.Request)
- func CopyReqBody(b io.ReadCloser) (r1, r2 io.ReadCloser, err error)
- func CopyRespBody(b *bytes.Buffer) (b1, b2 *bytes.Buffer, err error)
- func DecodeForm(v interface{}, values url.Values) (err error)
- func EncodeForm(v interface{}) (values url.Values, err error)
- func GetFormDecoder() *form.Decoder
- func GetFormEncoder() *form.Encoder
- func GetReqBody(cp io.ReadCloser, r *http.Request) string
- func GetRespBody(rec *httptest.ResponseRecorder) string
- func GetTranslator() ut.Translator
- func GetValidate() *validator.Validate
- func HandleBadRequestErr(err error)
- func HandleInternalServerError(err error)
- func Handler(name string) http.Handler
- func Index(w http.ResponseWriter, r *http.Request)
- func InitialiseRemoteConfigListener()
- func JsonMarshalIndent(data interface{}, prefix, indent string, disableHTMLEscape bool) (string, error)
- func NewHttpConfigListener() *httpConfigListener
- func NewResponseWriter(w http.ResponseWriter) *responseWriter
- func PanicBadRequestErr(err error)
- func PanicInternalServerError(err error)
- func Profile(w http.ResponseWriter, r *http.Request)
- func PrometheusMiddleware(next http.Handler) http.Handler
- func Proxy(proxyConfig ProxyConfig) func(inner http.Handler) http.Handler
- func RegisterFormDecoderCustomTypeFunc(fn form.DecodeCustomTypeFunc, types ...interface{})
- func RegisterFormEncoderCustomTypeFunc(fn form.EncodeCustomTypeFunc, types ...interface{})
- func SetTranslator(trans ut.Translator)
- func Symbol(w http.ResponseWriter, r *http.Request)
- func Trace(w http.ResponseWriter, r *http.Request)
- func UnWrap(err error) error
- func ValidateStruct(value interface{}) error
- func ValidateVar(value interface{}, tag, param string) error
- type BizError
- type BizErrorOption
- type DocItem
- type MiddlewareFunc
- type ProxyConfig
- type ProxyTarget
- type RestServer
- func (srv *RestServer) AddMiddleware(mwf ...func(http.Handler) http.Handler)
- func (srv *RestServer) AddRoute(route ...Route)
- func (srv *RestServer) AddRoutes(routes []Route, mwf ...func(http.Handler) http.Handler)
- func (srv *RestServer) GroupRoutes(group string, routes []Route, mwf ...func(http.Handler) http.Handler)
- func (srv *RestServer) Run()
- func (srv *RestServer) Serve(ln net.Listener)
- func (srv *RestServer) Use(mwf ...func(http.Handler) http.Handler)
- type Route
- type Row
- type ServerOption
Constants ¶
const ( HeaderAccept = "Accept" HeaderAcceptEncoding = "Accept-Encoding" HeaderAllow = "Allow" HeaderAuthorization = "Authorization" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLength = "Content-Length" HeaderContentType = "Content-Type" HeaderCookie = "Cookie" HeaderSetCookie = "Set-Cookie" HeaderIfModifiedSince = "If-Modified-Since" HeaderLastModified = "Last-Modified" HeaderLocation = "Location" HeaderUpgrade = "Upgrade" HeaderVary = "Vary" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderXForwardedFor = "X-Forwarded-For" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXForwardedProtocol = "X-Forwarded-Protocol" HeaderXForwardedSsl = "X-Forwarded-Ssl" HeaderXUrlScheme = "X-Url-Scheme" HeaderXHTTPMethodOverride = "X-HTTP-Method-Override" HeaderXRealIP = "X-Real-IP" HeaderXRequestID = "X-Request-ID" HeaderXRequestedWith = "X-Requested-With" HeaderServer = "Server" HeaderOrigin = "Origin" // Access control HeaderAccessControlRequestMethod = "Access-Control-Request-Method" HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" HeaderAccessControlMaxAge = "Access-Control-Max-Age" // Security HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXXSSProtection = "X-XSS-Protection" HeaderXFrameOptions = "X-Frame-Options" HeaderContentSecurityPolicy = "Content-Security-Policy" HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only" HeaderXCSRFToken = "X-CSRF-Token" HeaderReferrerPolicy = "Referrer-Policy" )
Headers borrowed from labstack/echo
Variables ¶
var ( Tracing = tracing Metrics = metrics Log = log BasicAuth = basicAuth Recovery = recovery )
var ConfigRoutes = configRoutes
var DocRoutes = docRoutes
var Docs []DocItem
window.docs = [ { "label": "Banana", "value": "http://localhost:6060/banana/go-doudou/doc", }, { "label": "Apple", "value": "http://localhost:6060/apple/go-doudou/doc", }
]
var PromRoutes = promRoutes
var RunnerChain = goresilience.RunnerChain
Functions ¶
func BulkHead ¶
BulkHead add bulk head pattern middleware based on https://github.com/slok/goresilience workers is the number of workers in the execution pool. maxWaitTime is the max time an incoming request will wait to execute before being dropped its execution and return 429 response.
func CallbackOnChange ¶
func CallbackOnChange(listener *httpConfigListener) func(event *configmgr.NacosChangeEvent)
func Cmdline ¶ added in v2.3.4
func Cmdline(w http.ResponseWriter, r *http.Request)
Cmdline responds with the running program's command line, with arguments separated by NUL bytes. The package initialization registers it as /debug/pprof/cmdline.
func CopyReqBody ¶
func CopyReqBody(b io.ReadCloser) (r1, r2 io.ReadCloser, err error)
borrowed from httputil unexported function drainBody
func DecodeForm ¶ added in v2.0.6
func EncodeForm ¶ added in v2.0.6
func GetFormDecoder ¶ added in v2.0.6
func GetFormEncoder ¶ added in v2.0.6
func GetReqBody ¶
func GetReqBody(cp io.ReadCloser, r *http.Request) string
func GetRespBody ¶
func GetRespBody(rec *httptest.ResponseRecorder) string
func GetTranslator ¶
func GetTranslator() ut.Translator
func GetValidate ¶
func GetValidate() *validator.Validate
func HandleBadRequestErr ¶ added in v2.0.6
func HandleBadRequestErr(err error)
func HandleInternalServerError ¶ added in v2.0.6
func HandleInternalServerError(err error)
func Handler ¶ added in v2.3.4
Handler returns an HTTP handler that serves the named profile. Available profiles can be found in runtime/pprof.Profile.
func Index ¶ added in v2.3.4
func Index(w http.ResponseWriter, r *http.Request)
Index responds with the pprof-formatted profile named by the request. For example, config.GddConfig.RouteRootPath + "/debug/pprof/heap" serves the "heap" profile. Index responds to a request for config.GddConfig.RouteRootPath + "/debug/pprof/" with an HTML page listing the available profiles.
func InitialiseRemoteConfigListener ¶
func InitialiseRemoteConfigListener()
func JsonMarshalIndent ¶
func NewHttpConfigListener ¶
func NewHttpConfigListener() *httpConfigListener
func NewResponseWriter ¶
func NewResponseWriter(w http.ResponseWriter) *responseWriter
NewResponseWriter creates new responseWriter
func PanicBadRequestErr ¶ added in v2.1.9
func PanicBadRequestErr(err error)
func PanicInternalServerError ¶ added in v2.1.9
func PanicInternalServerError(err error)
func Profile ¶ added in v2.3.4
func Profile(w http.ResponseWriter, r *http.Request)
Profile responds with the pprof-formatted cpu profile. Profiling lasts for duration specified in seconds GET parameter, or for 30 seconds if not specified. The package initialization registers it as /debug/pprof/profile.
func PrometheusMiddleware ¶
PrometheusMiddleware returns http HandlerFunc for prometheus matrix
func RegisterFormDecoderCustomTypeFunc ¶ added in v2.0.6
func RegisterFormDecoderCustomTypeFunc(fn form.DecodeCustomTypeFunc, types ...interface{})
func RegisterFormEncoderCustomTypeFunc ¶ added in v2.0.6
func RegisterFormEncoderCustomTypeFunc(fn form.EncodeCustomTypeFunc, types ...interface{})
func SetTranslator ¶
func SetTranslator(trans ut.Translator)
func Symbol ¶ added in v2.3.4
func Symbol(w http.ResponseWriter, r *http.Request)
Symbol looks up the program counters listed in the request, responding with a table mapping program counters to function names. The package initialization registers it as /debug/pprof/symbol.
func Trace ¶ added in v2.3.4
func Trace(w http.ResponseWriter, r *http.Request)
Trace responds with the execution trace in binary form. Tracing lasts for duration specified in seconds GET parameter, or for 1 second if not specified. The package initialization registers it as /debug/pprof/trace.
func ValidateStruct ¶
func ValidateStruct(value interface{}) error
func ValidateVar ¶
Types ¶
type BizError ¶
BizError is used for business error implemented error interface StatusCode will be set to http response status code ErrCode is used for business error code ErrMsg is custom error message
func NewBizError ¶
func NewBizError(err error, opts ...BizErrorOption) BizError
NewBizError is factory function for creating an instance of BizError struct
type BizErrorOption ¶
type BizErrorOption func(bizError *BizError)
func WithCause ¶
func WithCause(cause error) BizErrorOption
func WithErrCode ¶
func WithErrCode(errCode int) BizErrorOption
func WithStatusCode ¶
func WithStatusCode(statusCode int) BizErrorOption
type MiddlewareFunc ¶
func (MiddlewareFunc) Middleware ¶
func (mw MiddlewareFunc) Middleware(handler http.Handler) http.Handler
Middleware allows MiddlewareFunc to implement the middleware interface.
type ProxyConfig ¶
type ProxyTarget ¶
type RestServer ¶
RestServer wraps httpRouter router
func NewRestServer ¶
func NewRestServer(data ...map[string]interface{}) *RestServer
NewRestServer create a RestServer instance
func NewRestServerWithOptions ¶ added in v2.0.5
func NewRestServerWithOptions(options ...ServerOption) *RestServer
NewRestServerWithOptions create a RestServer instance with options
func (*RestServer) AddMiddleware ¶
func (srv *RestServer) AddMiddleware(mwf ...func(http.Handler) http.Handler)
AddMiddleware adds middlewares to the end of chain Deprecated: use Use instead
func (*RestServer) AddRoute ¶
func (srv *RestServer) AddRoute(route ...Route)
AddRoute adds routes to router
func (*RestServer) GroupRoutes ¶ added in v2.3.4
func (srv *RestServer) GroupRoutes(group string, routes []Route, mwf ...func(http.Handler) http.Handler)
GroupRoutes adds routes to router
func (*RestServer) Serve ¶ added in v2.2.5
func (srv *RestServer) Serve(ln net.Listener)
type Route ¶
type Route struct { Name string Method string Pattern string HandlerFunc http.HandlerFunc }
Route wraps config for route
func MemberlistUIRoutes ¶ added in v2.0.5
func MemberlistUIRoutes() []Route
type Row ¶ added in v2.0.5
type Row struct { Index int `json:"index"` SvcName string `json:"svcName"` Hostname string `json:"hostname"` BaseUrl string `json:"baseUrl"` Status string `json:"status"` Uptime string `json:"uptime"` GoVer string `json:"goVer"` GddVer string `json:"gddVer"` BuildUser string `json:"buildUser"` BuildTime string `json:"buildTime"` Data map[string]interface{} `json:"data"` Host string `json:"host"` SvcPort int `json:"svcPort"` MemPort int `json:"memPort"` }
type ServerOption ¶ added in v2.0.5
type ServerOption func(server *RestServer)
func WithPanicHandler ¶ added in v2.0.5
func WithPanicHandler(panicHandler func(inner http.Handler) http.Handler) ServerOption
func WithUserData ¶ added in v2.0.5
func WithUserData(userData map[string]interface{}) ServerOption
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package httprouter is a trie based high performance HTTP request router.
|
Package httprouter is a trie based high performance HTTP request router. |
Package lazyregexp is a thin wrapper over regexp, allowing the use of global regexp variables without forcing them to be compiled at init.
|
Package lazyregexp is a thin wrapper over regexp, allowing the use of global regexp variables without forcing them to be compiled at init. |
Package mock is a generated GoMock package.
|
Package mock is a generated GoMock package. |
Package profile provides a representation of github.com/google/pprof/proto/profile.proto and methods to encode/decode/merge profiles in this format.
|
Package profile provides a representation of github.com/google/pprof/proto/profile.proto and methods to encode/decode/merge profiles in this format. |