httpin

package module
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2021 License: MIT Imports: 10 Imported by: 25

README

httpin

Go documentation codecov Go Reference

HTTP Input for Go - Decode an HTTP request into a custom struct

Documentation

Quick View

Before (use net/http) After (use httpin)
func ListUsers(rw http.ResponseWriter, r *http.Request) {
	page, err := strconv.ParseInt(r.FormValue("page"), 10, 64)
	if err != nil {
		// Invalid parameter: page.
		return
	}
	perPage, err := strconv.ParseInt(r.FormValue("per_page"), 10, 64)
	if err != nil {
		// Invalid parameter: per_page.
		return
	}
	isMember, err := strconv.ParseBool(r.FormValue("is_member"))
	if err != nil {
		// Invalid parameter: is_member.
		return
	}

	// Do sth.
}
type ListUsersInput struct {
	Page     int  `in:"query=page"`
	PerPage  int  `in:"query=per_page"`
	IsMember bool `in:"query=is_member"`
}

func ListUsers(rw http.ResponseWriter, r *http.Request) {
	input := r.Context().Value(httpin.Input).(*ListUsersInput)
	// Do sth.
}

Why this package?

Items Before (use net/http package) After (use ggicci/httpin package)
Developer Time 😫 Expensive (too much parsing stuff code) 🚀 Faster (define the struct for receiving input data and leave the parsing job to httpin)
Code Repetition Rate 😞 High Lower
Code Readability 😟 Poor Highly readable
Maintainability 😡 Poor 😍 Highly maintainable

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrMissingField             = errors.New("missing required field")
	ErrUnsupporetedType         = errors.New("unsupported type")
	ErrUnregisteredExecutor     = errors.New("unregistered executor")
	ErrDuplicateTypeDecoder     = errors.New("duplicate type decoder")
	ErrNilTypeDecoder           = errors.New("nil type decoder")
	ErrDuplicateExecutor        = errors.New("duplicate executor")
	ErrNilExecutor              = errors.New("nil executor")
	ErrUnknownBodyType          = errors.New("unknown body type")
	ErrDuplicateAnnotationField = errors.New("duplicate annotation field")
	ErrNilErrorHandler          = errors.New("nil error handler")
)

Functions

func NewInput

func NewInput(inputStruct interface{}, opts ...Option) middleware

NewInput creates a "Middleware Constructor" for making a chain, which acts as a list of http.Handler constructors. We recommend using https://github.com/justinas/alice to chain your HTTP middleware functions and the app handler.

func RegisterDirectiveExecutor

func RegisterDirectiveExecutor(name string, exe DirectiveExecutor, norm DirectiveNormalizer)

RegisterDirectiveExecutor registers a named executor globally, which implemented the DirectiveExecutor interface. Will panic if the name were taken or nil executor.

func RegisterTypeDecoder added in v0.2.2

func RegisterTypeDecoder(typ reflect.Type, decoder TypeDecoder)

RegisterTypeDecoder registers a specific type decoder. Panics on conflicts.

func ReplaceDefaultErrorHandler added in v0.6.1

func ReplaceDefaultErrorHandler(custom ErrorHandler)

func ReplaceDirectiveExecutor

func ReplaceDirectiveExecutor(name string, exe DirectiveExecutor, norm DirectiveNormalizer)

ReplaceDirectiveExecutor works like RegisterDirectiveExecutor without panic on duplicate names.

func ReplaceTypeDecoder added in v0.2.2

func ReplaceTypeDecoder(typ reflect.Type, decoder TypeDecoder)

ReplaceTypeDecoder replaces a specific type decoder.

func UseGochiURLParam added in v0.3.0

func UseGochiURLParam(executor string, fn GochiURLParamFunc)

func UseGorillaMux

func UseGorillaMux(executor string, fnVars GorillaMuxVarsFunc)

UseGorillaMux registers a new directive executor which can extract path variables from the URL. Which works as an accompany to gorilla's mux package.

Example:

UseGorillaMux("path", mux.Vars)

type GetUserInput struct {
   UserID `httpin:"path=user_id"`
}

Types

type ContextKey

type ContextKey int
const (
	Input ContextKey = iota // the primary key to get the input object in the context injected by httpin

	// Set this context value to true to indicate that the field has been set.
	// When multiple executors were applied to a field, if the field value were set by
	// an executor, the latter executors may skip running by consulting this context value.
	FieldSet

	StopRecursion
)

type Directive added in v0.4.0

type Directive struct {
	Executor string   // name of the executor
	Argv     []string // argv
}

Directive defines the profile to locate an httpin.DirectiveExecutor instance and drive it with essential arguments.

func (*Directive) Execute added in v0.4.0

func (d *Directive) Execute(ctx *DirectiveContext) error

Execute locates the executor and runs it with the specified context.

type DirectiveContext

type DirectiveContext struct {
	Directive
	ValueType reflect.Type
	Value     reflect.Value
	Request   *http.Request
	Context   context.Context
}

DirectiveContext holds essential information about the field being resolved and the active HTTP request. Working as the context in a directive executor.

func (*DirectiveContext) DeliverContextValue

func (c *DirectiveContext) DeliverContextValue(key, value interface{})

DeliverContextValue binds a value to the specified key in the context. And it will be delivered among the executors in the same field resolver.

type DirectiveExecutor

type DirectiveExecutor interface {
	Execute(*DirectiveContext) error
}

DirectiveExecutor is the interface implemented by a "directive executor".

type DirectiveExecutorFunc

type DirectiveExecutorFunc func(*DirectiveContext) error

DirectiveExecutorFunc is an adpator to allow to use of ordinary functions as httpin.DirectiveExecutor.

func (DirectiveExecutorFunc) Execute

Execute calls f(ctx).

type DirectiveNormalizer added in v0.4.0

type DirectiveNormalizer interface {
	Normalize(*Directive) error
}

type DirectiveNormalizerFunc added in v0.4.0

type DirectiveNormalizerFunc func(*Directive) error

DirectiveNormalizerFunc is an adaptor to allow to use of ordinary functions as httpin.DirectiveNormalizer.

func (DirectiveNormalizerFunc) Normalize added in v0.4.0

func (f DirectiveNormalizerFunc) Normalize(dir *Directive) error

Normalize calls f(dir).

type Engine added in v0.2.1

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

Engine holds the information on how to decode a request to an instance of a concrete struct type.

func New

func New(inputStruct interface{}, opts ...Option) (*Engine, error)

New builds an HTTP request decoder for the specified struct type with custom options.

func (*Engine) Decode added in v0.2.1

func (e *Engine) Decode(req *http.Request) (interface{}, error)

Decode decodes an HTTP request to a struct instance.

type ErrorHandler added in v0.6.0

type ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error)

type GochiURLParamFunc added in v0.3.0

type GochiURLParamFunc func(r *http.Request, key string) string

GochiURLParamFunc is chi.URLParam

type GorillaMuxVarsFunc added in v0.3.0

type GorillaMuxVarsFunc func(*http.Request) map[string]string

GorillaMuxVarsFunc is mux.Vars

type InvalidFieldError

type InvalidFieldError struct {
	// Field is the name of the field.
	Field string `json:"field"`

	// Source is the directive which causes the error.
	// e.g. form, header, required, etc.
	Source string `json:"source"`

	// Value is the input data.
	Value interface{} `json:"value"`

	// ErrorMessage is the string representation of `internalError`.
	ErrorMessage string `json:"error"`

	// directives is the list of directives bound to the field.
	Directives []*Directive `json:"-"`
	// contains filtered or unexported fields
}

func (*InvalidFieldError) Error

func (f *InvalidFieldError) Error() string

func (*InvalidFieldError) Unwrap

func (f *InvalidFieldError) Unwrap() error

type JSONBody added in v0.4.0

type JSONBody struct{}

type Option added in v0.6.0

type Option func(*Engine) error

func WithErrorHandler added in v0.6.0

func WithErrorHandler(custom ErrorHandler) Option

WithErrorHandler overrides the default error handler.

type TypeDecoder added in v0.2.2

type TypeDecoder = internal.TypeDecoder

TypeDecoder is the interface implemented by types that can decode bytes to themselves.

type TypeDecoderFunc added in v0.2.2

type TypeDecoderFunc = internal.TypeDecoderFunc

TypeDecoderFunc is an adaptor to allow the use of ordinary functions as httpin TypeDecoders.

type UnsupportedTypeError

type UnsupportedTypeError struct {
	Type reflect.Type
}

func (UnsupportedTypeError) Error

func (e UnsupportedTypeError) Error() string

func (UnsupportedTypeError) Unwrap

func (e UnsupportedTypeError) Unwrap() error

type XMLBody added in v0.4.0

type XMLBody struct{}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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