rest

package
v2.3.1 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2024 License: MIT Imports: 65 Imported by: 22

Documentation

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

Oas store OpenAPI3.0 description json string

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

func (*RestServer) AddRoute

func (srv *RestServer) AddRoute(route ...Route)

AddRoute adds routes to router

func (*RestServer) PreMiddleware

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

PreMiddleware adds middlewares to the head of chain

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)

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 mock is a generated GoMock package.
Package mock is a generated GoMock package.

Jump to

Keyboard shortcuts

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