middleware

package
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2024 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	PERMISION_READ    = "PERMISION.READ"
	PERMISION_WRITE   = "PERMISION.WRITE"
	PERMISION_DELETE  = "PERMISION.DELETE"
	PERMISION_UPDATE  = "PERMISION.UPDATE"
	PERMISION_EXECUTE = "PERMISION.EXECUTE"
)
View Source
const (
	ERR_AUTORIZATION_IS_REQUIRED    = "Autorization is required"
	ERR_INVALID_AUTORIZATION_FORMAT = "Invalid autorization format"
)
View Source
const RequestIDKey ctxKeyRequestID = 0

RequestIDKey is the key that holds the unique request ID in a request context.

Variables

View Source
var (
	// LogEntryCtxKey is the context.Context key to store the request log entry.
	LogEntryCtxKey = sesion.ContextKey("LogEntry")

	// DefaultLogger is called by the Logger middleware handler to log each request.
	// Its made a package-level variable so that it can be reconfigured for custom
	// logging configurations.
	DefaultLogger func(next http.Handler) http.Handler
)
View Source
var RequestIDHeader = "X-Request-Id"

RequestIDHeader is the name of the HTTP Header which contains the request id. Exported so that it can be changed by developers

Functions

func AllowAll added in v0.0.9

func AllowAll(allowedOrigins []string) *cors.Cors

func Autentication added in v0.0.4

func Autentication(next http.Handler) http.Handler

* * Autentication * @param next http.Handler *

func Authorization

func Authorization(next http.Handler) http.Handler

* * Authorization * @param next http.Handler * @return http.Handler *

func GetAuthorization

func GetAuthorization(w http.ResponseWriter, r *http.Request) (string, error)

* * GetAuthorization * @param w http.ResponseWriter * @param r *http.Request * @return string * @return error *

func GetReqID

func GetReqID(ctx context.Context) string

GetReqID returns a request ID from the given context if one is present. Returns the empty string if a request ID cannot be found.

func Logger

func Logger(next http.Handler) http.Handler

Logger is a middleware that logs the start and end of each request, along with some useful data about what was requested, what the response status was, and how long it took to return. When standard output is a TTY, Logger will print in color, otherwise it will print in black and white. Logger prints a request ID if one is provided.

Alternatively, look at https://github.com/goware/httplog for a more in-depth http logger with structured logging support.

IMPORTANT NOTE: Logger should go before any other middleware that may change the response, such as `middleware.Recoverer`. Example:

```go r := chi.NewRouter() r.Use(middleware.Logger) // <--<< Logger should come before Recoverer r.Use(middleware.Recoverer) r.Get("/", handler) ```

func MethodAutorized added in v0.0.4

func MethodAutorized(p map[string]bool, r *http.Request) bool

func NewPermisions added in v0.0.4

func NewPermisions(data string) (map[string]bool, error)

* * NewPermisions * @param data string * @return map[string]bool, error *

func NextRequestID

func NextRequestID() uint64

NextRequestID generates the next request ID in the sequence.

func PermisionsToStr added in v0.0.4

func PermisionsToStr(p map[string]bool) string

* * PermisionsToStr * @param p map[string]bool * @return string *

func PrintPrettyStack

func PrintPrettyStack(rvr interface{})

func Recoverer

func Recoverer(next http.Handler) http.Handler

Recoverer is a middleware that recovers from panics, logs the panic (and a backtrace), and returns a HTTP 500 (Internal Server Error) status if possible. Recoverer prints a request ID if one is provided.

Alternatively, look at https://github.com/pressly/lg middleware pkgs.

func RequestID

func RequestID(next http.Handler) http.Handler

RequestID is a middleware that injects a request ID into the context of each request. A request ID is a string of the form "host.example.com/random-0001", where "random" is a base62 random string that uniquely identifies this go process, and where the last number is an atomically incremented request counter.

func RequestLogger

func RequestLogger(f LogFormatter) func(next http.Handler) http.Handler

RequestLogger returns a logger handler using a custom LogFormatter.

func SetAuthorizationFunc added in v0.0.4

func SetAuthorizationFunc(f AuthorizationFunc)

* * SetAuthorizationFunc * @param f AuthorizationFunc *

func SetServiceName added in v0.0.4

func SetServiceName(name string)

* * SetServiceName * @params name string *

func WithLogEntry

func WithLogEntry(r *http.Request, entry LogEntry) *http.Request

WithLogEntry sets the in-context LogEntry for a request.

Types

type AuthorizationFunc added in v0.0.4

type AuthorizationFunc func(profile et.Json) (map[string]bool, error)

type DefaultLogFormatter

type DefaultLogFormatter struct {
	Logger  LoggerInterface
	NoColor bool
}

DefaultLogFormatter is a simple logger that implements a LogFormatter.

func (*DefaultLogFormatter) NewLogEntry

func (l *DefaultLogFormatter) NewLogEntry(r *http.Request) LogEntry

NewLogEntry creates a new LogEntry for the request.

type LogEntry

type LogEntry interface {
	Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{})
	Panic(v interface{}, stack []byte)
}

LogEntry records the final log when a request completes. See defaultLogEntry for an example implementation.

func GetLogEntry

func GetLogEntry(r *http.Request) LogEntry

GetLogEntry returns the in-context LogEntry for a request.

type LogFormatter

type LogFormatter interface {
	NewLogEntry(r *http.Request) LogEntry
}

LogFormatter initiates the beginning of a new LogEntry per request. See DefaultLogFormatter for an example implementation.

type LoggerInterface

type LoggerInterface interface {
	Print(v ...interface{})
}

LoggerInterface accepts printing to stdlib logger or compatible logger.

type Metrics added in v0.0.3

type Metrics struct {
	TimeStamp    time.Time     `json:"timestamp"`
	ServiceName  string        `json:"service_name"`
	ReqID        string        `json:"req_id"`
	ClientIP     string        `json:"client_ip"`
	Scheme       string        `json:"scheme"`
	Host         string        `json:"host"`
	Method       string        `json:"method"`
	Path         string        `json:"path"`
	StatusCode   int           `json:"status_code"`
	ResponseSize int           `json:"response_size"`
	SearchTime   time.Duration `json:"search_time"`
	ResponseTime time.Duration `json:"response_time"`
	Latency      time.Duration `json:"latency"`
	// contains filtered or unexported fields
}

func NewMetric added in v0.0.3

func NewMetric(r *http.Request) *Metrics

* * NewMetric * @params r *http.Request * @return *Metrics *

func NewRpcMetric added in v0.0.4

func NewRpcMetric(method string) *Metrics

* * NewRpcMetric * @params method string * @return *Metrics *

func (*Metrics) CallLatency added in v0.0.4

func (m *Metrics) CallLatency()

* * CallLatency *

func (*Metrics) CallMetrics added in v0.0.4

func (m *Metrics) CallMetrics() Telemetry

* * CallMetrics * @return Telemetry *

func (*Metrics) CallResponseTime added in v0.0.4

func (m *Metrics) CallResponseTime()

* * CallResponseTime *

func (*Metrics) CallSearchTime added in v0.0.4

func (m *Metrics) CallSearchTime()

* * CallSearchTime *

func (*Metrics) DoneFn added in v0.0.3

func (m *Metrics) DoneFn(rw *ResponseWriterWrapper) et.Json

* * DoneFn * @params rw *ResponseWriterWrapper * @params r *http.Request * @return et.Json *

func (*Metrics) DoneHTTP added in v0.0.4

func (m *Metrics) DoneHTTP(rw *ResponseWriterWrapper) et.Json

* * DoneHTTP * @params rw *ResponseWriterWrapper * @return et.Json *

func (*Metrics) DoneRpc added in v0.0.4

func (m *Metrics) DoneRpc(r any) et.Json

* * DoneRpc * @params r et.Json * @return et.Json *

func (*Metrics) HTTPError added in v0.0.4

func (m *Metrics) HTTPError(w http.ResponseWriter, r *http.Request, statusCode int, message string) error

* * HTTPError * @params w http.ResponseWriter * @params r *http.Request * @params statusCode int * @params message string *

func (*Metrics) ITEM added in v0.0.4

func (m *Metrics) ITEM(w http.ResponseWriter, r *http.Request, statusCode int, dt et.Item) error

* * ITEM * @params w http.ResponseWriter * @params r *http.Request * @params statusCode int * @params dt et.Item *

func (*Metrics) ITEMS added in v0.0.4

func (m *Metrics) ITEMS(w http.ResponseWriter, r *http.Request, statusCode int, dt et.Items) error

* * ITEMS * @params w http.ResponseWriter * @params r *http.Request * @params statusCode int * @params dt et.Items *

func (*Metrics) JSON added in v0.0.4

func (m *Metrics) JSON(w http.ResponseWriter, r *http.Request, statusCode int, dt interface{}) error

* * JSON * @params w http.ResponseWriter * @params r *http.Request * @params statusCode int * @params dt interface{} *

func (*Metrics) SetPath added in v0.0.4

func (m *Metrics) SetPath(val string)

* * SetPath * @params val string *

func (*Metrics) ToJson added in v0.0.4

func (m *Metrics) ToJson() et.Json

* * ToJson * @return et.Json *

func (*Metrics) Unauthorized added in v0.0.3

func (m *Metrics) Unauthorized(w http.ResponseWriter, r *http.Request)

* * Unauthorized * @params w http.ResponseWriter * @params r *http.Request *

func (*Metrics) WriteResponse added in v0.0.4

func (m *Metrics) WriteResponse(w http.ResponseWriter, r *http.Request, statusCode int, e []byte) error

* * WriteResponse * @params w http.ResponseWriter * @params r *http.Request * @params statusCode int * @params e []byte *

type Request added in v0.0.3

type Request struct {
	Tag     string
	Day     int
	Hour    int
	Minute  int
	Seccond int
	Limit   int
}

type ResponseWriterWrapper added in v0.0.3

type ResponseWriterWrapper struct {
	http.ResponseWriter
	Size       int
	StatusCode int
}

func (*ResponseWriterWrapper) Write added in v0.0.3

func (rw *ResponseWriterWrapper) Write(b []byte) (int, error)

* * Write * @params b []byte *

type Result added in v0.0.4

type Result struct {
	Ok     bool        `json:"ok"`
	Result interface{} `json:"result"`
}

type Telemetry added in v0.0.4

type Telemetry struct {
	TimeStamp         string
	ServiceName       string
	Key               string
	RequestsPerSecond int
	RequestsPerMinute int
	RequestsPerHour   int
	RequestsPerDay    int
	RequestsLimit     int
}

func (*Telemetry) ToJson added in v0.0.4

func (m *Telemetry) ToJson() et.Json

* * ToJson * @return et.Json *

type WrapResponseWriter

type WrapResponseWriter interface {
	http.ResponseWriter
	// Status returns the HTTP status of the request, or 0 if one has not
	// yet been sent.
	Status() int
	// BytesWritten returns the total number of bytes sent to the client.
	BytesWritten() int
	// Tee causes the response body to be written to the given io.Writer in
	// addition to proxying the writes through. Only one io.Writer can be
	// tee'd to at once: setting a second one will overwrite the first.
	// Writes will be sent to the proxy before being written to this
	// io.Writer. It is illegal for the tee'd writer to be modified
	// concurrently with writes.
	Tee(io.Writer)
	// Unwrap returns the original proxied target.
	Unwrap() http.ResponseWriter
}

WrapResponseWriter is a proxy around an http.ResponseWriter that allows you to hook into various parts of the response process.

func NewWrapResponseWriter

func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter

NewWrapResponseWriter wraps an http.ResponseWriter, returning a proxy that allows you to hook into various parts of the response process.

Jump to

Keyboard shortcuts

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