rest

package
v2.3.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 20, 2024 License: MIT Imports: 71 Imported by: 22

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

View Source
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

View Source
var (
	Tracing   = tracing
	Metrics   = metrics
	Log       = log
	BasicAuth = basicAuth
	Recovery  = recovery
)
View Source
var ConfigRoutes = configRoutes
View Source
var DocRoutes = docRoutes
View Source
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",
}

]

View Source
var PromRoutes = promRoutes

Functions

func BodyMaxBytes

func BodyMaxBytes(n int64) func(inner http.Handler) http.Handler

func BulkHead

func BulkHead(workers int, maxWaitTime time.Duration) func(inner http.Handler) http.Handler

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 CopyRespBody

func CopyRespBody(b *bytes.Buffer) (b1, b2 *bytes.Buffer, err error)

func DecodeForm added in v2.0.6

func DecodeForm(v interface{}, values url.Values) (err error)

func EncodeForm added in v2.0.6

func EncodeForm(v interface{}) (values url.Values, err error)

func GetFormDecoder added in v2.0.6

func GetFormDecoder() *form.Decoder

func GetFormEncoder added in v2.0.6

func GetFormEncoder() *form.Encoder

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

func Handler(name string) http.Handler

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 JsonMarshalIndent(data interface{}, prefix, indent string, disableHTMLEscape bool) (string, error)

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

func PrometheusMiddleware(next http.Handler) http.Handler

PrometheusMiddleware returns http HandlerFunc for prometheus matrix

func Proxy

func Proxy(proxyConfig ProxyConfig) func(inner http.Handler) http.Handler

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 UnWrap added in v2.3.1

func UnWrap(err error) error

func ValidateStruct

func ValidateStruct(value interface{}) error

func ValidateVar

func ValidateVar(value interface{}, tag, param string) error

Types

type BizError

type BizError struct {
	StatusCode int
	ErrCode    int
	ErrMsg     string
	Cause      error
}

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

func (BizError) Error

func (b BizError) Error() string

Error is used for implementing error interface

func (BizError) String

func (b BizError) String() string

String function is used for printing string representation of a BizError instance

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 DocItem added in v2.3.4

type DocItem struct {
	Label string `json:"label"`
	Value string `json:"value"`
}

type MiddlewareFunc

type MiddlewareFunc func(http.Handler) http.Handler

func (MiddlewareFunc) Middleware

func (mw MiddlewareFunc) Middleware(handler http.Handler) http.Handler

Middleware allows MiddlewareFunc to implement the middleware interface.

type ProxyConfig

type ProxyConfig struct {
	ProviderStore cache.IStore
	// To customize the transport to remote.
	// Examples: If custom TLS certificates are required.
	Transport http.RoundTripper

	// ModifyResponse defines function to modify response from ProxyTarget.
	ModifyResponse func(*http.Response) error
}

type ProxyTarget

type ProxyTarget struct {
	Name string
	URL  *url.URL
}

type RestServer

type RestServer struct {
	*http.Server
	// contains filtered or unexported fields
}

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) AddRoutes added in v2.3.4

func (srv *RestServer) AddRoutes(routes []Route, mwf ...func(http.Handler) http.Handler)

AddRoutes 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) Run

func (srv *RestServer) Run()

Run runs http server

func (*RestServer) Serve added in v2.2.5

func (srv *RestServer) Serve(ln net.Listener)

func (*RestServer) Use added in v2.3.4

func (srv *RestServer) Use(mwf ...func(http.Handler) http.Handler)

Use adds middlewares to the end of chain

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"`
}

func NewRow added in v2.0.5

func NewRow(index int, service registry.Service, uptime string, meta registry.NodeMeta, node *memberlist.Node) Row

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

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL