uhttp

package module
v0.0.12 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2025 License: Apache-2.0 Imports: 16 Imported by: 14

README

uHTTP

This is a simple http utility package for sending, receiving and handling http requests and responses.

Documentation

Index

Constants

View Source
const (
	HeaderContentType = "Content-Type"
	HeaderRequestID   = "X-Request-ID"

	ContentTypeJSON = "application/json"
)

Variables

This section is empty.

Functions

func AuthHeaderFromContext

func AuthHeaderFromContext(ctx context.Context) string

AuthHeaderFromContext returns the Authorization HTTP header value from the provided context. If the header was not set it returns an empty string.

func AuthHeaderToContext

func AuthHeaderToContext(ctx context.Context, r *http.Request) context.Context

AuthHeaderToContext copies the Authorization HTTP header into the provided context.

func AuthHeaderToContextMux

func AuthHeaderToContextMux() func(http.Handler) http.Handler

AuthHeaderToContextMux returns a gorilla mux middleware which copies the Authorization HTTP header into the provided context.

func AuthToContext

func AuthToContext(ctx context.Context, value string) context.Context

AuthToContext puts the authorisation into the context directly.

func DecodeJSON

func DecodeJSON[T any](reader io.ReadCloser, v *T) error

func DecodeRequestJSON

func DecodeRequestJSON[T any](r *http.Request, v *T) error

func Encode

func Encode[T any](w http.ResponseWriter, status int, v T) error

Encode defaults to JSON encoding

func EncodeJSON

func EncodeJSON[T any](w http.ResponseWriter, status int, v T) error

EncodeJSON encodes a response as JSON

func GenerateOrCopyRequestID

func GenerateOrCopyRequestID(ctx context.Context, r *http.Request) context.Context

func GenerateOrCopyRequestIDMux

func GenerateOrCopyRequestIDMux() func(http.Handler) http.Handler

func GenerateRequestIDToContext

func GenerateRequestIDToContext(r *http.Request) context.Context

GenerateRequestIDToContext generates a new request ID and copies it into the provided context.

func GenericErrorHandler

func GenericErrorHandler(w http.ResponseWriter, r *http.Request, err error)

func InternalOnly

func InternalOnly(next http.Handler) http.HandlerFunc

func IsInternal

func IsInternal(r *http.Request) bool

IsInternal returns true if the request is internal.

func IsProxied

func IsProxied(r *http.Request) bool

IsProxied returns true if the request is from kubernetes.

func MethodNotAllowedHandler

func MethodNotAllowedHandler() http.HandlerFunc

MethodNotAllowedHandler returns a handler that returns a 405 response.

func MustEncode added in v0.0.5

func MustEncode[T any](w http.ResponseWriter, status int, v T)

MustEncode encodes a response as JSON and logs an error if it fails

func MustSendMessage added in v0.0.12

func MustSendMessage(w http.ResponseWriter, message string)

func MustSendMessageWithStatus added in v0.0.12

func MustSendMessageWithStatus(w http.ResponseWriter, status int, message string)

func NewMessage

func NewMessage(message string) *common.Message

NewMessage creates a new Message.

func NotFoundHandler

func NotFoundHandler() http.HandlerFunc

NotFoundHandler returns a handler that returns a 404 response.

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext returns the request ID HTTP header value from the provided context. If the header was not set it returns an empty string.

func RequestIDRawToContext

func RequestIDRawToContext(ctx context.Context, requestID string) context.Context

RequestIDRawToContext copies the provided request ID into the provided context.

func RequestIDToContext

func RequestIDToContext(ctx context.Context, r *http.Request) context.Context

RequestIDToContext copies the request ID HTTP header into the provided context. This should be used as a param to the transport/http.ServerBefore() (go-kit) func.

func RequestIDToContextMux

func RequestIDToContextMux() func(http.Handler) http.Handler

RequestIDToContextMux returns a gorilla mux middleware which copies the request ID HTTP header into the provided context.

func SendMessage

func SendMessage(w http.ResponseWriter, message string) error

func SendMessageWithStatus

func SendMessageWithStatus(w http.ResponseWriter, status int, message string) error

func UnauthorizedHandler

func UnauthorizedHandler() http.HandlerFunc

UnauthorizedHandler returns a handler that returns a 401 response.

func WrapHandler added in v0.0.12

func WrapHandler(handler http.HandlerFunc, middlewares ...MiddlewareFunc) http.Handler

WrapHandler wraps the handler with the specified middlewares, making the execution order the inverse of the parameter declaration.

Types

type ContextKey

type ContextKey string

ContextKey is key type for contexts.

type HTTPError added in v0.0.6

type HTTPError struct {
	common.ErrorMessage
	// contains filtered or unexported fields
}

func NewHTTPError added in v0.0.6

func NewHTTPError(code int, err error, details ...any) *HTTPError

NewHTTPError creates a new HTTPError.

func (*HTTPError) Error added in v0.0.6

func (e *HTTPError) Error() string

func (*HTTPError) SetRequestId added in v0.0.8

func (e *HTTPError) SetRequestId(requestId string)

func (*HTTPError) StatusCode added in v0.0.6

func (e *HTTPError) StatusCode() int

type MiddlewareFunc added in v0.0.12

type MiddlewareFunc = mux.MiddlewareFunc

MiddlewareFunc is a middleware function.

func InstrumentCounter added in v0.0.12

func InstrumentCounter(metric *prometheus.CounterVec) MiddlewareFunc

InstrumentCounter instruments a handler with the request counter, updating the supplied counter.

func InstrumentDuration added in v0.0.12

func InstrumentDuration(metric *prometheus.HistogramVec) MiddlewareFunc

InstrumentDuration instruments a handler with the request duration, updating the supplied histogram.

func InstrumentRequestSize added in v0.0.12

func InstrumentRequestSize(metric *prometheus.HistogramVec) MiddlewareFunc

InstrumentRequestSize instruments a handler with the request size, updating the supplied histogram.

func InstrumentResponseSize added in v0.0.12

func InstrumentResponseSize(metric *prometheus.HistogramVec) MiddlewareFunc

InstrumentResponseSize instruments a handler with the response size, updating the supplied histogram.

type MockRateLimiter

type MockRateLimiter struct {
	mock.Mock
}

MockRateLimiter is an autogenerated mock type for the RateLimiter type

func NewMockRateLimiter

func NewMockRateLimiter(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockRateLimiter

NewMockRateLimiter creates a new instance of MockRateLimiter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockRateLimiter) Allow

func (_m *MockRateLimiter) Allow(key string) bool

Allow provides a mock function with given fields: key

type MockStatusCoder added in v0.0.8

type MockStatusCoder struct {
	mock.Mock
}

MockStatusCoder is an autogenerated mock type for the StatusCoder type

func NewMockStatusCoder added in v0.0.8

func NewMockStatusCoder(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockStatusCoder

NewMockStatusCoder creates a new instance of MockStatusCoder. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockStatusCoder) StatusCode added in v0.0.8

func (_m *MockStatusCoder) StatusCode() int

StatusCode provides a mock function with no fields

type MockWriterOpt

type MockWriterOpt struct {
	mock.Mock
}

MockWriterOpt is an autogenerated mock type for the WriterOpt type

func NewMockWriterOpt

func NewMockWriterOpt(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockWriterOpt

NewMockWriterOpt creates a new instance of MockWriterOpt. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockWriterOpt) Execute

func (_m *MockWriterOpt) Execute(w *ResponseWriter)

Execute provides a mock function with given fields: w

type RateLimiter

type RateLimiter interface {
	// Allow returns true if the request is allowed.
	Allow(key string) bool
}

func NewRateLimiter

func NewRateLimiter(rps float64) RateLimiter

NewRateLimiter creates a new rate limiter.

rps is the requests per second.

func NewRateLimiterWithBurst

func NewRateLimiterWithBurst(rps float64, burst int) RateLimiter

NewRateLimiterWithBurst creates a new rate limiter.

rps is the requests per second.

burst is the burst. This is the number of requests that can be made in one go. If the burst is 0, then the burst is set to the rps. If the burst is less than the rps, then the burst is set to the rps.

type ResponseWriter

type ResponseWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

ResponseWriter is a wrapper around http.ResponseWriter that provides additional information. It is used to capture the status code and the number of bytes written. It also provides a way to determine if the header has been written.

func NewResponseWriter

func NewResponseWriter(w http.ResponseWriter, opts ...WriterOpt) *ResponseWriter

NewResponseWriter creates a new ResponseWriter.

func (*ResponseWriter) BytesWritten

func (c *ResponseWriter) BytesWritten() uint64

BytesWritten returns the number of bytes written.

func (*ResponseWriter) GetRequestDuration

func (c *ResponseWriter) GetRequestDuration() time.Duration

GetRequestDuration gets the duration of the request

func (*ResponseWriter) IsHeaderWritten

func (c *ResponseWriter) IsHeaderWritten() bool

IsHeaderWritten returns true if the header has been written.

func (*ResponseWriter) StatusCode

func (c *ResponseWriter) StatusCode() int

StatusCode returns the status code.

func (*ResponseWriter) Write

func (c *ResponseWriter) Write(p []byte) (bytes int, err error)

Write writes the data to the connection as part of an HTTP reply.

func (*ResponseWriter) WriteHeader

func (c *ResponseWriter) WriteHeader(code int)

WriteHeader sends an HTTP response header with the provided status code.

type StatusCoder added in v0.0.6

type StatusCoder interface {
	StatusCode() int
}

type WriterOpt

type WriterOpt func(w *ResponseWriter)

func WithDefaultContentType

func WithDefaultContentType(contentType string) WriterOpt

WithDefaultContentType sets the default content type for the response writer.

func WithDefaultHeader

func WithDefaultHeader(header, value string) WriterOpt

WithDefaultHeader sets the default headers for the response writer.

func WithDefaultHeaders

func WithDefaultHeaders(headers map[string]string) WriterOpt

func WithDefaultStatusCode

func WithDefaultStatusCode(statusCode int) WriterOpt

WithDefaultStatusCode sets the default status code for the response writer.

Directories

Path Synopsis
Package common provides primitives to interact with the openapi HTTP API.
Package common provides primitives to interact with the openapi HTTP API.

Jump to

Keyboard shortcuts

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