httpflow

package module
v0.0.0-...-3975a26 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2021 License: MIT Imports: 15 Imported by: 0

README

Barebones for common web applications:

  • Root directory contains various request handling helpers (JSON decoding, errors with status codes, etc.)
  • user package contains user auth/verification/recovery/etc. logic.
  • email package contains email sending functionality (useful when using user package)

cmd directory contains a working example backed by postgres database.

Documentation

Overview

Package httpflow provides helper functions and types to simplify work with HTTP requests.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnauthorized is returned when authorization process fails.
	ErrUnauthorized = NewError(nil, http.StatusUnauthorized, "")

	// ErrNotFound is returned when target resource is not found.
	ErrNotFound = NewError(nil, http.StatusNotFound, "")

	// ErrMethodNotAllowed is returned when request's method is not
	// supported for the requested endpoint.
	ErrMethodNotAllowed = NewError(nil, http.StatusMethodNotAllowed, "")
)
View Source
var (
	// ErrInvalidJSON is returned when request's body contains invalid
	// JSON data.
	ErrInvalidJSON = NewError(nil, http.StatusBadRequest, "invalid JSON body")

	// ErrInvalidForm is returned when request's form contains invalid
	// JSON data.
	ErrInvalidForm = NewError(nil, http.StatusBadRequest, "invalid form data")
)
View Source
var (
	// ErrInvalidFilterKey is returned when filter key is
	// determined to be invalid.
	ErrInvalidFilterKey = NewError(nil, http.StatusBadRequest, "invalid filter key")

	// ErrInvalidSortKey is returned when sort key is
	// determined to be invalid.
	ErrInvalidSortKey = NewError(nil, http.StatusBadRequest, "invalid sort key")
)

Functions

func DecodeForm

func DecodeForm(r *http.Request, v interface{}) error

DecodeForm decodes request's form values into destination object.

func DecodeJSON

func DecodeJSON(r *http.Request, v interface{}) error

DecodeJSON decodes request's JSON body into destination object.

func DetectError

func DetectError(err error) error

DetectError wraps the provided error with additional information useful for applications.

func ErrorCode

func ErrorCode(err error) int

ErrorCode returns status code associated with the error.

func ErrorMessage

func ErrorMessage(err error) string

ErrorMessage returns message associated with the error.

func ExtractIP

func ExtractIP(r *http.Request) (net.IP, error)

ExtractIP extracts request origin's IP address.

func ExtractParam

func ExtractParam(r *http.Request, p string) (string, error)

ExtractParam extracts a value by the the provided parameter name from the URL.

func ExtractSession

func ExtractSession(ctx context.Context) (sessionup.Session, xid.ID, error)

ExtractSession checks whether the session is present and returns it as well as user's ID.

func ExtractTargetID

func ExtractTargetID(r *http.Request) (xid.ID, error)

ExtractTargetID extracts ID from the URL.

func Location

func Location(loc string) func(http.Handler) http.Handler

Location is a middleware that adds or expands location header. It will only execute after the next http handler completes. If the location header is already present, it is not possible to overwrite it, but you may use {loc} in the provided location string to embed the previous value into the new one:

// Existing Location header: userID123
Location("/users/{loc}") // header will be set to "/users/userID123"

func MethodNotAllowed

func MethodNotAllowed(log zerolog.Logger) http.HandlerFunc

MethodNotAllowed handles cases when request's method is not supported for the requested endpoint.

func NewError

func NewError(err error, code int, msg string, args ...interface{}) error

NewError creates a new status error by optionally wrapping another error.

func NotFound

func NotFound(log zerolog.Logger) http.HandlerFunc

NotFound handles cases when request is sent to a non-existing endpoint.

func Respond

func Respond(log zerolog.Logger, w http.ResponseWriter, r *http.Request, data interface{}, code int)

Respond sends JSON type response to the client.

func RespondError

func RespondError(log zerolog.Logger, w http.ResponseWriter, r *http.Request, err error)

RespondError sends the provided error in a JSON format to the client.

func SessionReject

func SessionReject(log zerolog.Logger) func(error) http.Handler

SessionReject should be used as sessionup's rejection function.

Types

type LinkKey

type LinkKey string

LinkKey is used to access links in the map.

const (
	LinkActivation         LinkKey = "activation"
	LinkActivationCancel   LinkKey = "activation_cancel"
	LinkVerification       LinkKey = "verification"
	LinkVerificationCancel LinkKey = "verification_cancel"
	LinkRecovery           LinkKey = "recovery"
	LinkRecoveryCancel     LinkKey = "recovery_cancel"
)

Link-prefixed constants define core link keys.

type Links struct {
	// contains filtered or unexported fields
}

Links holds a map of link strings ready to formatted and built with arguments. Useful for sending emails etc. Strings should abide standard rules of formatting, example: "http://yoursite.com/user/activ?token=%s"

func NewLinks(ll map[LinkKey]string) Links

NewLinks creates a new link store.

func (Links) Exist

func (l Links) Exist(kk ...LinkKey) bool

Exist checks whether the links accessed by the specified keys exist or not.

func (Links) Prep

func (l Links) Prep(k LinkKey, args ...interface{}) string

Prep finds the link by the specified key and inserts all provided arguments into it (if allowed).

type Query

type Query struct {
	// Limit specifies the total amount of data elements per page.
	Limit uint64 `schema:"count"`

	// Page specifies data batch number.
	Page uint64 `schema:"page"`

	// FilterBy specifies a column by which filtering should be done.
	// If FilterVal is empty, no filtering should be done.
	// NOTE: should be checked before use.
	FilterBy string `schema:"filter_by"`

	// FilterVal specifies a string by which rows should be searched and
	// filtered.
	FilterVal string `schema:"filter_val"`

	// SortBy specifies which column should be used for sorting.
	// NOTE: should be checked before use.
	SortBy string `schema:"sort_by"`

	// Asc specifies whether ascending sorting order should be used.
	Asc bool `schema:"asc"`
}

Query is used to filter and retrieve bulk data from data stores.

func (Query) Validate

func (q Query) Validate(fck func(k, v string) error, sck func(k string) error) error

Validate checks whether query field values go out the bounds of sanity or not. First parameter should be filter key and value checking func, second - sort key checking func.

Directories

Path Synopsis
Package email provides email sending functionality.
Package email provides email sending functionality.
Package logutil provides helper functions for more convenient logging and error tracking.
Package logutil provides helper functions for more convenient logging and error tracking.
Package testutil implements helper functions for more convenient testing and may be imported in '_test.go' files only.
Package testutil implements helper functions for more convenient testing and may be imported in '_test.go' files only.
Package timeutil implements helper functions for time-related logic which extends the functionality of the standard time package.
Package timeutil implements helper functions for time-related logic which extends the functionality of the standard time package.
Package user provides user data handling functionality.
Package user provides user data handling functionality.
postgres
Package postgres provides functionality for interaction with postgres database.
Package postgres provides functionality for interaction with postgres database.

Jump to

Keyboard shortcuts

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