service

package
Version: v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2019 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// HighPriority for error type.
	// If an error occurs, ignore meta and data.
	HighPriority int = 100
	// MediumPriority for meta type.
	MediumPriority int = 200
	// LowPriority for data type.
	LowPriority int = 300
)

Variables

View Source
var FileForbidden = errors.Forbidden.Build("Nirvana:Service:FileForbidden", "can't access file ${path} because ${reason}")

FileForbidden is an error factory to show why can't access a file. This error may contains private information. Don't return this error to end users directly.

View Source
var FileNotFound = errors.NotFound.Build("Nirvana:Service:FileNotFound", "can't find file ${path} because ${reason}")

FileNotFound is an error factory to show why can't find a file. This error may contains private information. Don't return this error to end users directly.

View Source
var UnreadableFile = errors.InternalServerError.Build("Nirvana:Service:UnreadableFile", "can't read file ${path} because ${reason}")

UnreadableFile is an error factory to show why can't read a file. This error may contains private information. Don't return this error to end users directly.

View Source
var UnseekableFile = errors.InternalServerError.Build("Nirvana:Service:UnseekableFile", "can't seek file ${path} because ${reason}")

UnseekableFile is an error factory to show why can't seek a file. This error may contains private information. Don't return this error to end users directly.

Functions

func AcceptTypes

func AcceptTypes(req *http.Request) ([]string, error)

AcceptTypes is a util to get accept types from a request. Accept types are sorted by q.

func ContentType

func ContentType(req *http.Request) (string, error)

ContentType is a util to get content type from a request.

func ConvertToBool

func ConvertToBool(ctx context.Context, data []string) (interface{}, error)

ConvertToBool converts []string to bool. Only the first data is used.

func ConvertToBoolP

func ConvertToBoolP(ctx context.Context, data []string) (interface{}, error)

ConvertToBoolP converts []string to *bool. Only the first data is used.

func ConvertToBoolSlice

func ConvertToBoolSlice(ctx context.Context, data []string) (interface{}, error)

ConvertToBoolSlice converts all elements in data to bool, and return []bool

func ConvertToFloat32

func ConvertToFloat32(ctx context.Context, data []string) (interface{}, error)

ConvertToFloat32 converts []string to float32. Only the first data is used.

func ConvertToFloat32P

func ConvertToFloat32P(ctx context.Context, data []string) (interface{}, error)

ConvertToFloat32P converts []string to *float32. Only the first data is used.

func ConvertToFloat64

func ConvertToFloat64(ctx context.Context, data []string) (interface{}, error)

ConvertToFloat64 converts []string to float64. Only the first data is used.

func ConvertToFloat64P

func ConvertToFloat64P(ctx context.Context, data []string) (interface{}, error)

ConvertToFloat64P converts []string to *float64. Only the first data is used.

func ConvertToFloat64Slice

func ConvertToFloat64Slice(ctx context.Context, data []string) (interface{}, error)

ConvertToFloat64Slice converts all elements in data to float64, and return []float64

func ConvertToInt

func ConvertToInt(ctx context.Context, data []string) (interface{}, error)

ConvertToInt converts []string to int. Only the first data is used.

func ConvertToInt16

func ConvertToInt16(ctx context.Context, data []string) (interface{}, error)

ConvertToInt16 converts []string to int16. Only the first data is used.

func ConvertToInt16P

func ConvertToInt16P(ctx context.Context, data []string) (interface{}, error)

ConvertToInt16P converts []string to *int16. Only the first data is used.

func ConvertToInt32

func ConvertToInt32(ctx context.Context, data []string) (interface{}, error)

ConvertToInt32 converts []string to int32. Only the first data is used.

func ConvertToInt32P

func ConvertToInt32P(ctx context.Context, data []string) (interface{}, error)

ConvertToInt32P converts []string to *int32. Only the first data is used.

func ConvertToInt64

func ConvertToInt64(ctx context.Context, data []string) (interface{}, error)

ConvertToInt64 converts []string to int64. Only the first data is used.

func ConvertToInt64P

func ConvertToInt64P(ctx context.Context, data []string) (interface{}, error)

ConvertToInt64P converts []string to *int64. Only the first data is used.

func ConvertToInt8

func ConvertToInt8(ctx context.Context, data []string) (interface{}, error)

ConvertToInt8 converts []string to int8. Only the first data is used.

func ConvertToInt8P

func ConvertToInt8P(ctx context.Context, data []string) (interface{}, error)

ConvertToInt8P converts []string to *int8. Only the first data is used.

func ConvertToIntP

func ConvertToIntP(ctx context.Context, data []string) (interface{}, error)

ConvertToIntP converts []string to *int. Only the first data is used.

func ConvertToIntSlice

func ConvertToIntSlice(ctx context.Context, data []string) (interface{}, error)

ConvertToIntSlice converts all elements in data to int, and return []int

func ConvertToString

func ConvertToString(ctx context.Context, data []string) (interface{}, error)

ConvertToString return the first element in []string.

func ConvertToStringP

func ConvertToStringP(ctx context.Context, data []string) (interface{}, error)

ConvertToStringP return the first element's pointer in []string.

func ConvertToStringSlice

func ConvertToStringSlice(ctx context.Context, data []string) (interface{}, error)

ConvertToStringSlice return all strings in data.

func ConvertToUint

func ConvertToUint(ctx context.Context, data []string) (interface{}, error)

ConvertToUint converts []string to uint. Only the first data is used.

func ConvertToUint16

func ConvertToUint16(ctx context.Context, data []string) (interface{}, error)

ConvertToUint16 converts []string to uint16. Only the first data is used.

func ConvertToUint16P

func ConvertToUint16P(ctx context.Context, data []string) (interface{}, error)

ConvertToUint16P converts []string to *uint16. Only the first data is used.

func ConvertToUint32

func ConvertToUint32(ctx context.Context, data []string) (interface{}, error)

ConvertToUint32 converts []string to uint32. Only the first data is used.

func ConvertToUint32P

func ConvertToUint32P(ctx context.Context, data []string) (interface{}, error)

ConvertToUint32P converts []string to *uint32. Only the first data is used.

func ConvertToUint64

func ConvertToUint64(ctx context.Context, data []string) (interface{}, error)

ConvertToUint64 converts []string to uint64. Only the first data is used.

func ConvertToUint64P

func ConvertToUint64P(ctx context.Context, data []string) (interface{}, error)

ConvertToUint64P converts []string to *uint64. Only the first data is used.

func ConvertToUint8

func ConvertToUint8(ctx context.Context, data []string) (interface{}, error)

ConvertToUint8 converts []string to uint8. Only the first data is used.

func ConvertToUint8P

func ConvertToUint8P(ctx context.Context, data []string) (interface{}, error)

ConvertToUint8P converts []string to *uint8. Only the first data is used.

func ConvertToUintP

func ConvertToUintP(ctx context.Context, data []string) (interface{}, error)

ConvertToUintP converts []string to *uint. Only the first data is used.

func HTTPCodeFor

func HTTPCodeFor(m definition.Method) int

HTTPCodeFor gets a success status code for specified definition method.

func HTTPMethodFor

func HTTPMethodFor(m definition.Method) string

HTTPMethodFor gets a HTTP method for specified definition method.

func MetaForContentType added in v0.2.0

func MetaForContentType(ctype string) map[string]string

MetaForContentType returns a meta for content type.

func ReadFile added in v0.2.0

func ReadFile(path string) (string, io.ReadCloser, error)

ReadFile reads file and returns mime type.

func RegisterConsumer

func RegisterConsumer(c Consumer) error

RegisterConsumer register a consumer. A consumer must not handle "*/*".

func RegisterConverter

func RegisterConverter(typ reflect.Type, converter Converter)

RegisterConverter registers a converter for specified type. New converter overrides old one.

func RegisterDestinationHandler

func RegisterDestinationHandler(handler DestinationHandler) error

RegisterDestinationHandler registers a type handler.

func RegisterMethod

func RegisterMethod(method definition.Method, httpMethod string, code int) error

RegisterMethod registers a HTTP method and a success status code for a definition method.

func RegisterParameterGenerator

func RegisterParameterGenerator(generator ParameterGenerator) error

RegisterParameterGenerator register a generator.

func RegisterPrefab

func RegisterPrefab(prefab Prefab) error

RegisterPrefab registers a prefab.

func RegisterProducer

func RegisterProducer(p Producer) error

RegisterProducer register a producer. A producer must not handle "*/*".

func WrapHTTPHandler

func WrapHTTPHandler(h http.Handler) func(ctx context.Context)

WrapHTTPHandler wraps an http handler to definition function.

func WrapHTTPHandlerFunc

func WrapHTTPHandlerFunc(f http.HandlerFunc) func(ctx context.Context)

WrapHTTPHandlerFunc wraps an http handler func to definition function.

func WriteData

func WriteData(ctx context.Context, producers []Producer, code int, data interface{}) error

WriteData chooses right producer by "Accrpt" header and writes data to context. You should never call the function except you are writing a type handler.

Types

type AutoParameterConfig added in v0.2.0

type AutoParameterConfig map[AutoParameterConfigKey]string

AutoParameterConfig contains configs of AutoParameter.

func ParseAutoParameterTag added in v0.2.0

func ParseAutoParameterTag(tag string) (source definition.Source, name string, apc AutoParameterConfig, err error)

ParseAutoParameterTag parse the tag of AutoParameter.

func (AutoParameterConfig) Get added in v0.2.0

Get gets value of a config key.

func (AutoParameterConfig) Set added in v0.2.0

Set sets value for a config key.

type AutoParameterConfigKey added in v0.2.0

type AutoParameterConfigKey string

AutoParameterConfigKey is the key of AutoParameterConfig.

const (
	// AutoParameterConfigKeyDefaultValue is the key of default value.
	AutoParameterConfigKeyDefaultValue AutoParameterConfigKey = "default"
	// AutoParameterConfigKeyAnonymous is the prefix of anonymous configs.
	AutoParameterConfigKeyAnonymous AutoParameterConfigKey = " anonymous"
)

type AutoParameterGenerator

type AutoParameterGenerator struct{}

AutoParameterGenerator generates an object from a struct type. The fields in a struct can have tag. Tag name is "source". Its value format is "Source,Name".

ex. type Example struct {

Start       int    `source:"Query,start"`
ContentType string `source:"Header,Content-Type"`

}

func (*AutoParameterGenerator) Generate

func (g *AutoParameterGenerator) Generate(ctx context.Context, vc ValueContainer, consumers []Consumer, name string, target reflect.Type) (interface{}, error)

func (*AutoParameterGenerator) Source

func (*AutoParameterGenerator) Validate

func (g *AutoParameterGenerator) Validate(name string, defaultValue interface{}, target reflect.Type) error

type BodyParameterGenerator

type BodyParameterGenerator struct{}

BodyParameterGenerator is used to generate object or body reader by value from request body.

func (*BodyParameterGenerator) Generate

func (g *BodyParameterGenerator) Generate(ctx context.Context, vc ValueContainer, consumers []Consumer,
	name string, target reflect.Type) (interface{}, error)

func (*BodyParameterGenerator) Source

func (*BodyParameterGenerator) Validate

func (g *BodyParameterGenerator) Validate(name string, defaultValue interface{}, target reflect.Type) error

type Builder

type Builder interface {
	// Logger returns logger of builder.
	Logger() log.Logger
	// SetLogger sets logger to server.
	SetLogger(logger log.Logger)
	// Modifier returns modifier of builder.
	Modifier() DefinitionModifier
	// SetModifier sets definition modifier.
	SetModifier(m DefinitionModifier)
	// Filters returns all request filters.
	Filters() []Filter
	// AddFilters add filters to filter requests.
	AddFilter(filters ...Filter)
	// AddDescriptors adds descriptors to router.
	AddDescriptor(descriptors ...definition.Descriptor) error
	// Middlewares returns all router middlewares.
	Middlewares() map[string][]definition.Middleware
	// Definitions returns all definitions. If a modifier exists, it will be executed.
	Definitions() map[string][]definition.Definition
	// Build builds a service to handle request.
	Build() (Service, error)
}

Builder builds service.

func NewBuilder

func NewBuilder() Builder

NewBuilder creates a service builder.

type Consumer

type Consumer interface {
	// ContentType returns a HTTP MIME type.
	ContentType() string
	// Consume unmarshals data from r into v.
	Consume(r io.Reader, v interface{}) error
}

Consumer handles specifically typed data from a reader and unmarshals it into an object.

func AllConsumers

func AllConsumers() []Consumer

AllConsumers returns all consumers.

func ConsumerFor

func ConsumerFor(contentType string) Consumer

ConsumerFor gets a consumer for specified content type.

type ContextPrefab

type ContextPrefab struct{}

ContextPrefab returns context from parameter of Make(). It's usually used for generating the first parameter of api handler.

func (*ContextPrefab) Make

func (p *ContextPrefab) Make(ctx context.Context) (interface{}, error)

Make returns context simply.

func (*ContextPrefab) Name

func (p *ContextPrefab) Name() string

Name returns prefab name.

func (*ContextPrefab) Type

func (p *ContextPrefab) Type() reflect.Type

Type is type of context.Context.

type Converter

type Converter func(ctx context.Context, data []string) (interface{}, error)

Converter is used to convert []string to specific type. Data must have one element at least or it will panic.

func ConverterFor

func ConverterFor(typ reflect.Type) Converter

ConverterFor gets converter for specified type.

type DataDestinationHandler

type DataDestinationHandler struct{}

DataDestinationHandler writes value to http.ResponseWriter. The type handler handle object value. If value is nil, the handler does nothing.

func (*DataDestinationHandler) Destination

func (*DataDestinationHandler) Handle

func (h *DataDestinationHandler) Handle(ctx context.Context, producers []Producer, code int, value interface{}) (goon bool, err error)

func (*DataDestinationHandler) Priority

func (h *DataDestinationHandler) Priority() int

func (*DataDestinationHandler) Validate

func (h *DataDestinationHandler) Validate(target reflect.Type) error

type DefinitionModifier

type DefinitionModifier func(d *definition.Definition)

DefinitionModifier is used in Server. It's used to modify definition. If you want to add some common data into all definitions, you can write a customized modifier for it.

func ConsumeAllIfConsumesIsEmpty

func ConsumeAllIfConsumesIsEmpty() DefinitionModifier

ConsumeAllIfConsumesIsEmpty adds definition.MIMEAll to consumes if consumes is empty.

func ConsumeNoneForHTTPDelete

func ConsumeNoneForHTTPDelete() DefinitionModifier

ConsumeNoneForHTTPDelete adds definition.MIMENone to consumes for delete definitions. Then you don't need to manually write the consume to every delete definitions. The delete is http delete rather than definition.Delete.

func ConsumeNoneForHTTPGet

func ConsumeNoneForHTTPGet() DefinitionModifier

ConsumeNoneForHTTPGet adds definition.MIMENone to consumes for get definitions. Then you don't need to manually write the consume to every get definitions. The get is http get rather than definition.Get.

func FirstContextParameter

func FirstContextParameter() DefinitionModifier

FirstContextParameter adds a context prefab parameter into all definitions. Then you don't need to manually write the parameter to every definitions.

func LastErrorResult

func LastErrorResult() DefinitionModifier

LastErrorResult adds a error result into all definitions. Then you don't need to manually write the result to every definitions.

func ProduceAllIfProducesIsEmpty

func ProduceAllIfProducesIsEmpty() DefinitionModifier

ProduceAllIfProducesIsEmpty adds definition.MIMEAll to consumes if consumes is empty.

func ProduceNoneForHTTPDelete

func ProduceNoneForHTTPDelete() DefinitionModifier

ProduceNoneForHTTPDelete adds definition.MIMENone to produces for delete definitions. Then you don't need to manually write the produce to every delete definitions. The delete is http delete rather than definition.Delete.

type DefinitionModifiers

type DefinitionModifiers []DefinitionModifier

DefinitionModifiers is a convenient type for []DefinitionModifier

func (DefinitionModifiers) Combine

Combine combines a list of modifiers to one.

type DestinationHandler

type DestinationHandler interface {
	// Type returns definition.Type which the type handler can handle.
	Destination() definition.Destination
	// Priority returns priority of the type handler. Type handler with higher priority will prior execute.
	Priority() int
	// Validate validates whether the type handler can handle the target type.
	Validate(target reflect.Type) error
	// Handle handles a value. If the handler has something wrong, it should return an error.
	// The handler descides how to deal with value by producers and status code.
	// The status code is a success status code. If everything is ok, the handler should use the status code.
	//
	// There are three cases for return values (goon means go on or continue):
	// 1. go on is true, err is nil.
	//    It means that current type handler did nothing (or looks like did nothing) and next type handler
	//    should take the context.
	// 2. go on is false, err is nil.
	//    It means that current type handler has finished the context and next type handler should not run.
	// 3. err is not nil
	//    It means that current type handler handled the context but something wrong. All subsequent type
	//    handlers should not run.
	Handle(ctx context.Context, producers []Producer, code int, value interface{}) (goon bool, err error)
}

DestinationHandler is used to handle the results from API handlers.

func DestinationHandlerFor

func DestinationHandlerFor(typ definition.Destination) DestinationHandler

DestinationHandlerFor gets a type handler for specified type.

type Error

type Error interface {
	// Code is a HTTP status code.
	Code() int
	// Message is an object which contains information of the error.
	Message() interface{}
}

Error is a common interface for error. If an error implements the interface, type handlers can use Code() to get a specified HTTP status code.

type ErrorDestinationHandler

type ErrorDestinationHandler struct{}

ErrorDestinationHandler writes error to http.ResponseWriter. If there is no error, the handler does nothing.

func (*ErrorDestinationHandler) Destination

func (*ErrorDestinationHandler) Handle

func (h *ErrorDestinationHandler) Handle(ctx context.Context, producers []Producer, code int, value interface{}) (goon bool, err error)

func (*ErrorDestinationHandler) Priority

func (h *ErrorDestinationHandler) Priority() int

func (*ErrorDestinationHandler) Validate

func (h *ErrorDestinationHandler) Validate(target reflect.Type) error

type FileParameterGenerator

type FileParameterGenerator struct {
}

FileParameterGenerator is used to generate file reader by value from request form file.

func (*FileParameterGenerator) Generate

func (g *FileParameterGenerator) Generate(ctx context.Context, vc ValueContainer, consumers []Consumer,
	name string, target reflect.Type) (interface{}, error)

func (*FileParameterGenerator) Source

func (*FileParameterGenerator) Validate

func (g *FileParameterGenerator) Validate(name string, defaultValue interface{}, target reflect.Type) error

type Filter

type Filter func(resp http.ResponseWriter, req *http.Request) bool

Filter can filter request. It has the highest priority in a request lifecycle. It runs before router matching. If a filter return false, that means the request should be filtered. If a filter want to filter a request, it should handle the request by itself.

func FillLeadingSlash

func FillLeadingSlash() Filter

FillLeadingSlash returns a pseudo filter to fill a leading slash when a request path does not have a leading slash. The filter won't filter anything.

func ParseRequestForm

func ParseRequestForm() Filter

ParseRequestForm returns a filter to parse request form when content type is "application/x-www-form-urlencoded" or "multipart/form-data". The filter won't filter anything unless some error occurs in parsing.

func RedirectTrailingSlash

func RedirectTrailingSlash() Filter

RedirectTrailingSlash returns a filter to redirect request. If a request has trailing slash like `some-url/`, the filter will redirect the request to `some-url`.

type FormDataConsumer

type FormDataConsumer struct{ RawSerializer }

FormDataConsumer implements Consumer for content type "multipart/form-data"

func (*FormDataConsumer) Consume

func (s *FormDataConsumer) Consume(r io.Reader, v interface{}) error

Consume reads data and converts it to string, []byte.

func (*FormDataConsumer) ContentType

func (s *FormDataConsumer) ContentType() string

ContentType returns form data MIME type.

type FormParameterGenerator

type FormParameterGenerator struct{}

FormParameterGenerator is used to generate object by value from request form.

func (*FormParameterGenerator) Generate

func (g *FormParameterGenerator) Generate(ctx context.Context, vc ValueContainer, consumers []Consumer,
	name string, target reflect.Type) (interface{}, error)

func (*FormParameterGenerator) Source

func (*FormParameterGenerator) Validate

func (g *FormParameterGenerator) Validate(name string, defaultValue interface{}, target reflect.Type) error

type HTTPContext

type HTTPContext interface {
	Request() *http.Request
	ResponseWriter() ResponseWriter
	ValueContainer() ValueContainer
	RoutePath() string
	// contains filtered or unexported methods
}

HTTPContext describes an http context.

func HTTPContextFrom

func HTTPContextFrom(ctx context.Context) HTTPContext

HTTPContextFrom get http context from context.

type HeaderParameterGenerator

type HeaderParameterGenerator struct{}

HeaderParameterGenerator is used to generate object by value from request header.

func (*HeaderParameterGenerator) Generate

func (g *HeaderParameterGenerator) Generate(ctx context.Context, vc ValueContainer, consumers []Consumer,
	name string, target reflect.Type) (interface{}, error)

func (*HeaderParameterGenerator) Source

func (*HeaderParameterGenerator) Validate

func (g *HeaderParameterGenerator) Validate(name string, defaultValue interface{}, target reflect.Type) error

type JSONSerializer

type JSONSerializer struct{ RawSerializer }

JSONSerializer implements Consumer and Producer for content type "application/json".

func (*JSONSerializer) Consume

func (s *JSONSerializer) Consume(r io.Reader, v interface{}) error

Consume unmarshals json from r into v.

func (*JSONSerializer) ContentType

func (s *JSONSerializer) ContentType() string

ContentType returns json MIME type.

func (*JSONSerializer) Produce

func (s *JSONSerializer) Produce(w io.Writer, v interface{}) error

Produce marshals v to json and write to w.

type MetaDestinationHandler

type MetaDestinationHandler struct{}

MetaDestinationHandler writes metadata to http.ResponseWriter.Header and value type should be map[string]string. If value type is not map, the handler will stop the handlers chain and return an error. If there is no error, it always expect that the next handler goes on.

func (*MetaDestinationHandler) Destination

func (*MetaDestinationHandler) Handle

func (h *MetaDestinationHandler) Handle(ctx context.Context, producers []Producer, code int, value interface{}) (goon bool, err error)

func (*MetaDestinationHandler) Priority

func (h *MetaDestinationHandler) Priority() int

func (*MetaDestinationHandler) Validate

func (h *MetaDestinationHandler) Validate(target reflect.Type) error

type NoneSerializer

type NoneSerializer struct{}

NoneSerializer implements Consumer and Producer for content types which can only receive data by io.Reader.

func (*NoneSerializer) Consume

func (s *NoneSerializer) Consume(r io.Reader, v interface{}) error

Consume does nothing.

func (*NoneSerializer) ContentType

func (s *NoneSerializer) ContentType() string

ContentType returns none MIME type.

func (*NoneSerializer) Produce

func (s *NoneSerializer) Produce(w io.Writer, v interface{}) error

Produce does nothing.

type ParameterGenerator

type ParameterGenerator interface {
	// Source returns the source generated by current generator.
	Source() definition.Source
	// Validate validates whether defaultValue and target type is valid.
	Validate(name string, defaultValue interface{}, target reflect.Type) error
	// Generate generates an object by data from value container.
	Generate(ctx context.Context, vc ValueContainer, consumers []Consumer, name string, target reflect.Type) (interface{}, error)
}

ParameterGenerator is used to generate object for a parameter.

func ParameterGeneratorFor

func ParameterGeneratorFor(source definition.Source) ParameterGenerator

ParameterGeneratorFor gets a parameter generator for specified source.

type PathParameterGenerator

type PathParameterGenerator struct{}

PathParameterGenerator is used to generate object by value from path

func (*PathParameterGenerator) Generate

func (g *PathParameterGenerator) Generate(ctx context.Context, vc ValueContainer, consumers []Consumer,
	name string, target reflect.Type) (interface{}, error)

func (*PathParameterGenerator) Source

func (*PathParameterGenerator) Validate

func (g *PathParameterGenerator) Validate(name string, defaultValue interface{}, target reflect.Type) error

type Prefab

type Prefab interface {
	// Name returns prefab name.
	Name() string
	// Type is instance type.
	Type() reflect.Type
	// Make makes an instance.
	Make(ctx context.Context) (interface{}, error)
}

Prefab creates instances for internal type. These instances are not unmarshaled form http request data.

func PrefabFor

func PrefabFor(name string) Prefab

PrefabFor gets a prefab by name.

type PrefabParameterGenerator

type PrefabParameterGenerator struct{}

PrefabParameterGenerator is used to generate object by prefabs.

func (*PrefabParameterGenerator) Generate

func (g *PrefabParameterGenerator) Generate(ctx context.Context, vc ValueContainer, consumers []Consumer,
	name string, target reflect.Type) (interface{}, error)

func (*PrefabParameterGenerator) Source

func (*PrefabParameterGenerator) Validate

func (g *PrefabParameterGenerator) Validate(name string, defaultValue interface{}, target reflect.Type) error

type Producer

type Producer interface {
	// ContentType returns a HTTP MIME type.
	ContentType() string
	// Produce marshals v to data and write to w.
	Produce(w io.Writer, v interface{}) error
}

Producer marshals an object to specifically typed data and write it into a writer.

func AllProducers

func AllProducers() []Producer

AllProducers returns all producers.

func ProducerFor

func ProducerFor(contentType string) Producer

ProducerFor gets a producer for specified content type.

type QueryParameterGenerator

type QueryParameterGenerator struct{}

QueryParameterGenerator is used to generate object by value from query string.

func (*QueryParameterGenerator) Generate

func (g *QueryParameterGenerator) Generate(ctx context.Context, vc ValueContainer, consumers []Consumer,
	name string, target reflect.Type) (interface{}, error)

func (*QueryParameterGenerator) Source

func (*QueryParameterGenerator) Validate

func (g *QueryParameterGenerator) Validate(name string, defaultValue interface{}, target reflect.Type) error

type RawSerializer

type RawSerializer struct{}

RawSerializer implements a raw serializer.

func (*RawSerializer) CanConsumeData

func (s *RawSerializer) CanConsumeData(contentType string, r io.Reader, v interface{}) bool

CanConsumeData checks if raw serializer can consume type v with specified content type.

func (*RawSerializer) CanProduceData

func (s *RawSerializer) CanProduceData(contentType string, w io.Writer, v interface{}) bool

CanProduceData checks if raw serializer can produce data for specified content type from type v.

func (*RawSerializer) ConsumeData

func (s *RawSerializer) ConsumeData(contentType string, r io.Reader, v interface{}) error

ConsumeData reads data and converts it to string, []byte.

func (*RawSerializer) ProduceData

func (s *RawSerializer) ProduceData(contentType string, w io.Writer, v interface{}) error

ProduceData writes v to writer. v should be string, []byte, io.Reader.

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	// HeaderWritable can check whether WriteHeader() has
	// been called. If the method returns false, you should
	// not recall WriteHeader().
	HeaderWritable() bool
	// StatusCode returns status code.
	StatusCode() int
	// ContentLength returns the length of written content.
	ContentLength() int
}

ResponseWriter extends http.ResponseWriter.

type Service

type Service interface {
	http.Handler
}

Service handles HTTP requests.

Workflow:

  Service.ServeHTTP()
----------------------
↓                    ↑

|-----Filters------| ↑

↓                    ↑

|---Router Match---| ↑

↓                    ↑

|-------------Middlewares------------|

↓                    ↑

|-------------Executor---------------|

↓                    ↑

|-ParameterGenerators-|-DestinationHandlers-|

↓                    ↑

|------------User Function-----------|

type SimpleSerializer added in v0.2.0

type SimpleSerializer struct {
	RawSerializer
	// contains filtered or unexported fields
}

SimpleSerializer implements a simple serializer.

func NewSimpleSerializer added in v0.2.0

func NewSimpleSerializer(contentType string) *SimpleSerializer

NewSimpleSerializer creates a simple serializer.

func (*SimpleSerializer) Consume added in v0.2.0

func (s *SimpleSerializer) Consume(r io.Reader, v interface{}) error

Consume reads data and converts it to string, []byte.

func (*SimpleSerializer) ContentType added in v0.2.0

func (s *SimpleSerializer) ContentType() string

ContentType returns plain text MIME type.

func (*SimpleSerializer) Produce added in v0.2.0

func (s *SimpleSerializer) Produce(w io.Writer, v interface{}) error

Produce writes v to writer. v should be string, []byte, io.Reader.

type URLEncodedConsumer

type URLEncodedConsumer struct{ RawSerializer }

URLEncodedConsumer implements Consumer for content type "application/x-www-form-urlencoded"

func (*URLEncodedConsumer) Consume

func (s *URLEncodedConsumer) Consume(r io.Reader, v interface{}) error

Consume reads data and converts it to string, []byte.

func (*URLEncodedConsumer) ContentType

func (s *URLEncodedConsumer) ContentType() string

ContentType returns url encoded MIME type.

type ValueContainer

type ValueContainer interface {
	// Path returns path value by key.
	Path(key string) (string, bool)
	// Query returns value from query string.
	Query(key string) ([]string, bool)
	// Header returns value by header key.
	Header(key string) ([]string, bool)
	// Form returns value from request. It is valid when
	// http "Content-Type" is "application/x-www-form-urlencoded"
	// or "multipart/form-data".
	Form(key string) ([]string, bool)
	// File returns a file reader when "Content-Type" is "multipart/form-data".
	File(key string) (multipart.File, bool)
	// Body returns a reader to read data from request body.
	// The reader only can read once.
	Body() (reader io.ReadCloser, contentType string, ok bool)
}

ValueContainer contains values from a request.

type XMLSerializer

type XMLSerializer struct{ RawSerializer }

XMLSerializer implements Consumer and Producer for content type "application/xml".

func (*XMLSerializer) Consume

func (s *XMLSerializer) Consume(r io.Reader, v interface{}) error

Consume unmarshals xml from r into v.

func (*XMLSerializer) ContentType

func (s *XMLSerializer) ContentType() string

ContentType returns xml MIME type.

func (*XMLSerializer) Produce

func (s *XMLSerializer) Produce(w io.Writer, v interface{}) error

Produce marshals v to xml and write to w.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL