http

package
v0.0.0-...-d96fe47 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2024 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultErrorHandler = func(_ context.Context, err error) (HttpResponse, error) {
	e := err
	for {
		if httpErr, ok := e.(ErrorResponse); ok {
			b, err := httpErr.HttpBody()
			if err != nil {
				break
			}
			return HttpResponse{
				StatusCode: httpErr.HttpStatusCode(),
				Headers:    httpErr.HttpHeaders(),
				Body:       b,
			}, nil
		}
		if e = errors.Unwrap(e); e == nil {
			break
		}
	}
	return HttpResponse{
		StatusCode: http.StatusInternalServerError,
		Body:       []byte(`{"message":"Internal Server Error"}`),
	}, nil
}

DefaultErrorHandler is the default error handler for the lambda function. If th error implements ErrorResponse, it will return an HttpResponse with the status code, headers and body. If the error does not implement ErrorResponse, it will return a generic internal server error message.

The original error message is not returned to avoid accidentally leaking sensitive information.

View Source
var (
	ErrKeyNotFound = errors.New("key not found")
)

Functions

func StartV1

func StartV1[Req any, Resp any](handler Handler[Req, Resp], opts ...HttpOption)

StartV1 will start the lambda function with the given handler and options.

The handler is a function that receives a context and a pointer to a Context.

func StartV2

func StartV2[Req any, Resp any](handler Handler[Req, Resp], opts ...HttpOption)

StartV2 will start the lambda function with the given handler and options.

The handler is a function that receives a context and a pointer to a Context.

Types

type APIGatewayProxyRequest

type APIGatewayProxyRequest struct {
	Resource                        string                               `json:"resource"` // The resource path defined in API Gateway
	Path                            string                               `json:"path"`     // The url path for the caller
	HTTPMethod                      string                               `json:"httpMethod"`
	Headers                         map[string]string                    `json:"headers"`
	MultiValueHeaders               map[string][]string                  `json:"multiValueHeaders"`
	QueryStringParameters           map[string]string                    `json:"queryStringParameters"`
	MultiValueQueryStringParameters map[string][]string                  `json:"multiValueQueryStringParameters"`
	PathParameters                  map[string]string                    `json:"pathParameters"`
	StageVariables                  map[string]string                    `json:"stageVariables"`
	RequestContext                  events.APIGatewayProxyRequestContext `json:"requestContext"`
	Body                            string                               `json:"body"`
	IsBase64Encoded                 bool                                 `json:"isBase64Encoded,omitempty"`
}

APIGatewayProxyRequest contains data coming from the API Gateway proxy

type APIGatewayProxyResponse

type APIGatewayProxyResponse struct {
	StatusCode int               `json:"statusCode"`
	Headers    map[string]string `json:"headers"`
	Body       json.RawMessage   `json:"body"`
}

APIGatewayProxyResponse configures the response to be returned by API Gateway for the request

type APIGatewayV2HTTPResponse

type APIGatewayV2HTTPResponse struct {
	StatusCode        int                 `json:"statusCode"`
	Headers           map[string]string   `json:"headers"`
	MultiValueHeaders map[string][]string `json:"multiValueHeaders"`
	Body              string              `json:"body"`
	IsBase64Encoded   bool                `json:"isBase64Encoded,omitempty"`
	Cookies           []string            `json:"cookies"`
}

type Context

type Context[Req any, Resp any] struct {
	Context  context.Context
	Request  *Request[Req]
	Response *Response[Resp]
	Locals   map[string]any
	// contains filtered or unexported fields
}

func (*Context[Req, Resp]) Error

func (l *Context[Req, Resp]) Error() string

func (*Context[Req, Resp]) GetLocal

func (l *Context[Req, Resp]) GetLocal(key string) (any, bool)

func (*Context[Req, Resp]) Is

func (l *Context[Req, Resp]) Is(err error) bool

func (*Context[Req, Resp]) SetLocal

func (l *Context[Req, Resp]) SetLocal(key string, value any) *Context[Req, Resp]

func (*Context[Req, Resp]) UnsetLocal

func (l *Context[Req, Resp]) UnsetLocal(key string) *Context[Req, Resp]
type Cookie struct {
	Name        string
	Value       string
	Path        string
	Domain      string
	MaxAge      int
	Expires     time.Time
	Secure      bool
	HTTPOnly    bool
	SameSite    CookieSameSite
	SessionOnly bool
}

func (*Cookie) String

func (c *Cookie) String() string

type CookieSameSite

type CookieSameSite string
const (
	CookieSameSiteDefaultMode CookieSameSite = "SameSite"
	CookieSameSiteLaxMode     CookieSameSite = "Lax"
	CookieSameSiteStrictMode  CookieSameSite = "Strict"
	CookieSameSiteNoneMode    CookieSameSite = "None"
)

type Error

type Error struct {
	StatusCode int
	Headers    map[string]string
	Message    string
}

Error is a struct that implements ErrorResponse. It represents an error that can be returned by the lambda function.

func (*Error) Error

func (h *Error) Error() string

func (*Error) HttpBody

func (h *Error) HttpBody() (json.RawMessage, error)

func (*Error) HttpHeaders

func (h *Error) HttpHeaders() map[string]string

func (*Error) HttpStatusCode

func (h *Error) HttpStatusCode() int

type ErrorResponse

type ErrorResponse interface {
	HttpStatusCode() int
	HttpHeaders() map[string]string
	HttpBody() (json.RawMessage, error)
}

type Handler

type Handler[Req any, Resp any] func(*Context[Req, Resp]) error

func Use

func Use[Req any, Resp any](handler Handler[Req, Resp], middlewares ...Middleware[Req, Resp]) Handler[Req, Resp]

type Headers

type Headers = mapUtils

type HttpOption

type HttpOption func(*options)

func WithErrorHandler

func WithErrorHandler(h func(context.Context, error) (HttpResponse, error)) HttpOption

WithErrorHandler is an option that allows you to pass a custom error handler to the lambda function.

func WithResources

func WithResources(r ...Resource) HttpOption

WithResources is an option that allows you to pass resources to the lambda function.

type HttpResponse

type HttpResponse struct {
	StatusCode int
	Headers    map[string]string
	Body       json.RawMessage
}

type Middleware

type Middleware[Req any, Resp any] func(ctx *Context[Req, Resp], next Handler[Req, Resp]) error

type None

type None struct{}

type PathParams

type PathParams map[string]string

func (PathParams) Bool

func (p PathParams) Bool(key string) (bool, error)

func (PathParams) Float64

func (p PathParams) Float64(key string) (float64, error)

func (PathParams) Int

func (p PathParams) Int(key string) (int, error)

func (PathParams) Int64

func (p PathParams) Int64(key string) (int64, error)

func (PathParams) String

func (p PathParams) String(key string) (string, bool)

type Query

type Query = mapUtils

type Request

type Request[T any] struct {
	HTTPMethod string
	Path       string
	PathParams PathParams
	Query      Query
	Headers    Headers

	Body T
	// contains filtered or unexported fields
}

func (*Request[T]) Cookie

func (r *Request[T]) Cookie(key string) (string, bool)

type Resource

type Resource interface {
	Name() string
	Start(context.Context) error
}

type Response

type Response[T any] struct {
	StatusCode int
	Headers    map[string]string
	Cookies    []Cookie
	Body       bytes.Buffer
	Err        error
}

func (*Response[T]) Error

func (r *Response[T]) Error() string

func (*Response[T]) Header

func (r *Response[T]) Header(key string, value string) *Response[T]

func (*Response[T]) JSON

func (r *Response[T]) JSON(data any) *Response[T]

func (*Response[T]) Redirect

func (r *Response[T]) Redirect(url string, status ...int) *Response[T]

func (*Response[T]) SendString

func (r *Response[T]) SendString(data string) *Response[T]

func (*Response[T]) SetCookie

func (r *Response[T]) SetCookie(c Cookie) *Response[T]

func (*Response[T]) Status

func (r *Response[T]) Status(status int) *Response[T]

func (*Response[T]) UnsetCookie

func (r *Response[T]) UnsetCookie(name string) *Response[T]

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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