Documentation ¶
Index ¶
- Constants
- Variables
- func AcceptTypes(req *http.Request) ([]string, error)
- func ContentType(req *http.Request) (string, error)
- func ConvertToBool(ctx context.Context, data []string) (interface{}, error)
- func ConvertToBoolP(ctx context.Context, data []string) (interface{}, error)
- func ConvertToBoolSlice(ctx context.Context, data []string) (interface{}, error)
- func ConvertToFloat32(ctx context.Context, data []string) (interface{}, error)
- func ConvertToFloat32P(ctx context.Context, data []string) (interface{}, error)
- func ConvertToFloat64(ctx context.Context, data []string) (interface{}, error)
- func ConvertToFloat64P(ctx context.Context, data []string) (interface{}, error)
- func ConvertToFloat64Slice(ctx context.Context, data []string) (interface{}, error)
- func ConvertToInt(ctx context.Context, data []string) (interface{}, error)
- func ConvertToInt16(ctx context.Context, data []string) (interface{}, error)
- func ConvertToInt16P(ctx context.Context, data []string) (interface{}, error)
- func ConvertToInt32(ctx context.Context, data []string) (interface{}, error)
- func ConvertToInt32P(ctx context.Context, data []string) (interface{}, error)
- func ConvertToInt64(ctx context.Context, data []string) (interface{}, error)
- func ConvertToInt64P(ctx context.Context, data []string) (interface{}, error)
- func ConvertToInt8(ctx context.Context, data []string) (interface{}, error)
- func ConvertToInt8P(ctx context.Context, data []string) (interface{}, error)
- func ConvertToIntP(ctx context.Context, data []string) (interface{}, error)
- func ConvertToIntSlice(ctx context.Context, data []string) (interface{}, error)
- func ConvertToString(ctx context.Context, data []string) (interface{}, error)
- func ConvertToStringP(ctx context.Context, data []string) (interface{}, error)
- func ConvertToStringSlice(ctx context.Context, data []string) (interface{}, error)
- func ConvertToTime(ctx context.Context, data []string) (interface{}, error)
- func ConvertToTimeP(ctx context.Context, data []string) (interface{}, error)
- func ConvertToUint(ctx context.Context, data []string) (interface{}, error)
- func ConvertToUint16(ctx context.Context, data []string) (interface{}, error)
- func ConvertToUint16P(ctx context.Context, data []string) (interface{}, error)
- func ConvertToUint32(ctx context.Context, data []string) (interface{}, error)
- func ConvertToUint32P(ctx context.Context, data []string) (interface{}, error)
- func ConvertToUint64(ctx context.Context, data []string) (interface{}, error)
- func ConvertToUint64P(ctx context.Context, data []string) (interface{}, error)
- func ConvertToUint8(ctx context.Context, data []string) (interface{}, error)
- func ConvertToUint8P(ctx context.Context, data []string) (interface{}, error)
- func ConvertToUintP(ctx context.Context, data []string) (interface{}, error)
- func HTTPCodeFor(m definition.Method) int
- func HTTPMethodFor(m definition.Method) string
- func MetaForContentType(ctype string) map[string]string
- func ReadFile(path string) (string, io.ReadCloser, error)
- func RegisterConsumer(c Consumer) error
- func RegisterConverter(typ reflect.Type, converter Converter)
- func RegisterDestinationHandler(handler DestinationHandler) error
- func RegisterMethod(method definition.Method, httpMethod string, code int) error
- func RegisterParameterGenerator(generator ParameterGenerator) error
- func RegisterPrefab(prefab Prefab) error
- func RegisterProducer(p Producer) error
- func WrapHTTPHandler(h http.Handler) func(ctx context.Context)
- func WrapHTTPHandlerFunc(f http.HandlerFunc) func(ctx context.Context)
- func WriteData(ctx context.Context, producers []Producer, code int, data interface{}) error
- func WriteError(ctx context.Context, producers []Producer, err interface{}) error
- type APIStyle
- type AutoParameterConfig
- type AutoParameterConfigKey
- type AutoParameterGenerator
- func (g *AutoParameterGenerator) Generate(ctx context.Context, vc ValueContainer, consumers []Consumer, name string, ...) (interface{}, error)
- func (g *AutoParameterGenerator) Source() definition.Source
- func (g *AutoParameterGenerator) Validate(name string, defaultValue interface{}, target reflect.Type) error
- type BodyParameterGenerator
- func (g *BodyParameterGenerator) Generate(ctx context.Context, vc ValueContainer, consumers []Consumer, name string, ...) (interface{}, error)
- func (g *BodyParameterGenerator) Source() definition.Source
- func (g *BodyParameterGenerator) Validate(name string, defaultValue interface{}, target reflect.Type) error
- type Builder
- type Consumer
- type ContextPrefab
- type Converter
- type DataDestinationHandler
- func (h *DataDestinationHandler) Destination() definition.Destination
- func (h *DataDestinationHandler) Handle(ctx context.Context, producers []Producer, code int, value interface{}) (goon bool, err error)
- func (h *DataDestinationHandler) Priority() int
- func (h *DataDestinationHandler) Validate(target reflect.Type) error
- type DefinitionModifier
- func ConsumeAllIfConsumesIsEmpty() DefinitionModifier
- func ConsumeNoneForHTTPDelete() DefinitionModifier
- func ConsumeNoneForHTTPGet() DefinitionModifier
- func ConsumeNoneForHTTPHead() DefinitionModifier
- func FirstContextParameter() DefinitionModifier
- func LastErrorResult() DefinitionModifier
- func ProduceAllIfProducesIsEmpty() DefinitionModifier
- func ProduceNoneForHTTPDelete() DefinitionModifier
- func ProduceNoneForHTTPHead() DefinitionModifier
- type DefinitionModifiers
- type DestinationHandler
- type Error
- type ErrorDestinationHandler
- func (h *ErrorDestinationHandler) Destination() definition.Destination
- func (h *ErrorDestinationHandler) Handle(ctx context.Context, producers []Producer, code int, value interface{}) (goon bool, err error)
- func (h *ErrorDestinationHandler) Priority() int
- func (h *ErrorDestinationHandler) Validate(target reflect.Type) error
- type FileParameterGenerator
- func (g *FileParameterGenerator) Generate(ctx context.Context, vc ValueContainer, consumers []Consumer, name string, ...) (interface{}, error)
- func (g *FileParameterGenerator) Source() definition.Source
- func (g *FileParameterGenerator) Validate(name string, defaultValue interface{}, target reflect.Type) error
- type Filter
- type FormDataConsumer
- type FormParameterGenerator
- func (g *FormParameterGenerator) Generate(ctx context.Context, vc ValueContainer, consumers []Consumer, name string, ...) (interface{}, error)
- func (g *FormParameterGenerator) Source() definition.Source
- func (g *FormParameterGenerator) Validate(name string, defaultValue interface{}, target reflect.Type) error
- type HTTPContext
- type HTTPCtx
- type HeaderParameterGenerator
- func (g *HeaderParameterGenerator) Generate(ctx context.Context, vc ValueContainer, consumers []Consumer, name string, ...) (interface{}, error)
- func (g *HeaderParameterGenerator) Source() definition.Source
- func (g *HeaderParameterGenerator) Validate(name string, defaultValue interface{}, target reflect.Type) error
- type JSONSerializer
- type MetaDestinationHandler
- func (h *MetaDestinationHandler) Destination() definition.Destination
- func (h *MetaDestinationHandler) Handle(ctx context.Context, producers []Producer, code int, value interface{}) (goon bool, err error)
- func (h *MetaDestinationHandler) Priority() int
- func (h *MetaDestinationHandler) Validate(target reflect.Type) error
- type NoneSerializer
- type ParameterGenerator
- type PathParameterGenerator
- func (g *PathParameterGenerator) Generate(ctx context.Context, vc ValueContainer, consumers []Consumer, name string, ...) (interface{}, error)
- func (g *PathParameterGenerator) Source() definition.Source
- func (g *PathParameterGenerator) Validate(name string, defaultValue interface{}, target reflect.Type) error
- type Prefab
- type PrefabParameterGenerator
- func (g *PrefabParameterGenerator) Generate(ctx context.Context, vc ValueContainer, consumers []Consumer, name string, ...) (interface{}, error)
- func (g *PrefabParameterGenerator) Source() definition.Source
- func (g *PrefabParameterGenerator) Validate(name string, defaultValue interface{}, target reflect.Type) error
- type Producer
- type QueryParameterGenerator
- func (g *QueryParameterGenerator) Generate(ctx context.Context, vc ValueContainer, consumers []Consumer, name string, ...) (interface{}, error)
- func (g *QueryParameterGenerator) Source() definition.Source
- func (g *QueryParameterGenerator) Validate(name string, defaultValue interface{}, target reflect.Type) error
- type RawSerializer
- func (s *RawSerializer) CanConsumeData(contentType string, r io.Reader, v interface{}) bool
- func (s *RawSerializer) CanProduceData(contentType string, w io.Writer, v interface{}) bool
- func (s *RawSerializer) ConsumeData(contentType string, r io.Reader, v interface{}) error
- func (s *RawSerializer) ProduceData(contentType string, w io.Writer, v interface{}) error
- type ResponseWriter
- type Service
- type SimpleSerializer
- type URLEncodedConsumer
- type ValueContainer
- type XMLSerializer
Constants ¶
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 ¶
var ( // InvalidService represents no response error. InvalidService = errors.InternalServerError.Build("Nirvana:Service:NoResponse", "no response") // NoContext means can't find http context. NoContext = errors.InternalServerError.Build("Nirvana:Service:NoContext", "can't find http context, you should define `ctx context.Context` as the first parameter of your handler function") // NoParameterGenerator represents no parameter generator error. NoParameterGenerator = errors.InternalServerError.Build("Nirvana:Service:NoParameterGenerator", "no parameter generator for source ${source}") // NoProducerToWrite represents no producer to write error. NoProducerToWrite = errors.NotAcceptable.Build("Nirvana:Service:noProducerToWrite", "can't find producer for accept types ${types}") )
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.
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.
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.
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 ¶
AcceptTypes is a util to get accept types from a request. Accept types are sorted by q.
func ContentType ¶
ContentType is a util to get content type from a request.
func ConvertToBool ¶
ConvertToBool converts []string to bool. Only the first data is used.
func ConvertToBoolP ¶
ConvertToBoolP converts []string to *bool. Only the first data is used.
func ConvertToBoolSlice ¶
ConvertToBoolSlice converts all elements in data to bool, and return []bool
func ConvertToFloat32 ¶
ConvertToFloat32 converts []string to float32. Only the first data is used.
func ConvertToFloat32P ¶
ConvertToFloat32P converts []string to *float32. Only the first data is used.
func ConvertToFloat64 ¶
ConvertToFloat64 converts []string to float64. Only the first data is used.
func ConvertToFloat64P ¶
ConvertToFloat64P converts []string to *float64. Only the first data is used.
func ConvertToFloat64Slice ¶
ConvertToFloat64Slice converts all elements in data to float64, and return []float64
func ConvertToInt ¶
ConvertToInt converts []string to int. Only the first data is used.
func ConvertToInt16 ¶
ConvertToInt16 converts []string to int16. Only the first data is used.
func ConvertToInt16P ¶
ConvertToInt16P converts []string to *int16. Only the first data is used.
func ConvertToInt32 ¶
ConvertToInt32 converts []string to int32. Only the first data is used.
func ConvertToInt32P ¶
ConvertToInt32P converts []string to *int32. Only the first data is used.
func ConvertToInt64 ¶
ConvertToInt64 converts []string to int64. Only the first data is used.
func ConvertToInt64P ¶
ConvertToInt64P converts []string to *int64. Only the first data is used.
func ConvertToInt8 ¶
ConvertToInt8 converts []string to int8. Only the first data is used.
func ConvertToInt8P ¶
ConvertToInt8P converts []string to *int8. Only the first data is used.
func ConvertToIntP ¶
ConvertToIntP converts []string to *int. Only the first data is used.
func ConvertToIntSlice ¶
ConvertToIntSlice converts all elements in data to int, and return []int
func ConvertToString ¶
ConvertToString return the first element in []string.
func ConvertToStringP ¶
ConvertToStringP return the first element's pointer in []string.
func ConvertToStringSlice ¶
ConvertToStringSlice return all strings in data.
func ConvertToTime ¶ added in v0.2.10
ConvertToTime converts []string to time.Time. Only the first data is used.
func ConvertToTimeP ¶ added in v0.2.10
ConvertToTimeP return the first element's pointer in []string.
func ConvertToUint ¶
ConvertToUint converts []string to uint. Only the first data is used.
func ConvertToUint16 ¶
ConvertToUint16 converts []string to uint16. Only the first data is used.
func ConvertToUint16P ¶
ConvertToUint16P converts []string to *uint16. Only the first data is used.
func ConvertToUint32 ¶
ConvertToUint32 converts []string to uint32. Only the first data is used.
func ConvertToUint32P ¶
ConvertToUint32P converts []string to *uint32. Only the first data is used.
func ConvertToUint64 ¶
ConvertToUint64 converts []string to uint64. Only the first data is used.
func ConvertToUint64P ¶
ConvertToUint64P converts []string to *uint64. Only the first data is used.
func ConvertToUint8 ¶
ConvertToUint8 converts []string to uint8. Only the first data is used.
func ConvertToUint8P ¶
ConvertToUint8P converts []string to *uint8. Only the first data is used.
func ConvertToUintP ¶
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
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 ¶
RegisterConsumer register a consumer. A consumer must not handle "*/*".
func RegisterConverter ¶
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 RegisterProducer ¶
RegisterProducer register a producer. A producer must not handle "*/*".
func WrapHTTPHandler ¶
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.
Types ¶
type APIStyle ¶ added in v0.3.0
type APIStyle string
APIStyle defines the API style type of the builder.
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
func (f AutoParameterConfig) Get(key AutoParameterConfigKey) (string, bool)
Get gets value of a config key.
func (AutoParameterConfig) Set ¶ added in v0.2.0
func (f AutoParameterConfig) Set(key AutoParameterConfigKey, value string)
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" // AutoParameterConfigKeyOptional is the key of optional tag. AutoParameterConfigKeyOptional AutoParameterConfigKey = "optional" )
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)
Generate generates an object by data from value container.
func (*AutoParameterGenerator) Source ¶
func (g *AutoParameterGenerator) Source() definition.Source
Source returns the source generated by current generator.
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)
Generate generates an object by data from value container.
func (*BodyParameterGenerator) Source ¶
func (g *BodyParameterGenerator) Source() definition.Source
Source returns the source generated by current generator.
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 // AddFilter add filters to filter requests. AddFilter(filters ...Filter) // AddDescriptor adds descriptors to router. AddDescriptor(descriptors ...interface{}) error // Definitions returns all definitions. If a modifier exists, it will be executed. Definitions() map[string][]definition.Definition // APIStyle returns the API style of this builder. APIStyle() APIStyle // Build builds a service to handle request. Build() (Service, error) }
Builder builds service.
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 ConsumerFor ¶
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) Type ¶
func (p *ContextPrefab) Type() reflect.Type
Type is type of context.Context.
type Converter ¶
Converter is used to convert []string to specific type. Data must have one element at least or it will panic.
func ConverterFor ¶
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 (h *DataDestinationHandler) Destination() definition.Destination
Destination returns definition.Destination which the destination handler can handle.
func (*DataDestinationHandler) Handle ¶
func (h *DataDestinationHandler) Handle(ctx context.Context, producers []Producer, code int, value interface{}) (goon bool, err error)
Handle handles a value. If the handler has something wrong, it should return an error.
func (*DataDestinationHandler) Priority ¶
func (h *DataDestinationHandler) Priority() int
Priority returns priority of the type handler.
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 ConsumeNoneForHTTPHead ¶ added in v0.2.10
func ConsumeNoneForHTTPHead() DefinitionModifier
ConsumeNoneForHTTPHead adds definition.MIMENone to consumes for head definitions. Then you don't need to manually write the consume to every head definitions. The head is http head rather than definition.Head.
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 produces and errorProduces if they are 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.
func ProduceNoneForHTTPHead ¶ added in v0.2.10
func ProduceNoneForHTTPHead() DefinitionModifier
ProduceNoneForHTTPHead adds definition.MIMENone to produces for head definitions. Then you don't need to manually write the produce to every head definitions. The head is http head rather than definition.Head.
type DefinitionModifiers ¶
type DefinitionModifiers []DefinitionModifier
DefinitionModifiers is a convenient type for []DefinitionModifier
func (DefinitionModifiers) Combine ¶
func (m DefinitionModifiers) Combine() DefinitionModifier
Combine combines a list of modifiers to one.
type DestinationHandler ¶
type DestinationHandler interface { // Destination returns definition.Destination which the destination 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 (h *ErrorDestinationHandler) Destination() definition.Destination
Destination returns definition.Destination which the destination handler can handle.
func (*ErrorDestinationHandler) Handle ¶
func (h *ErrorDestinationHandler) Handle(ctx context.Context, producers []Producer, code int, value interface{}) (goon bool, err error)
Handle handles a value. If the handler has something wrong, it should return an error.
func (*ErrorDestinationHandler) Priority ¶
func (h *ErrorDestinationHandler) Priority() int
Priority returns priority of the type handler.
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)
Generate generates an object by data from value container.
func (*FileParameterGenerator) Source ¶
func (g *FileParameterGenerator) Source() definition.Source
Source returns the source generated by current generator.
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. Same as ParseRequestFormWithMaxMemory, except that maxMemory is set to 32MB by default.
func ParseRequestFormWithMaxMemory ¶ added in v0.2.5
ParseRequestFormWithMaxMemory 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)
Generate generates an object by data from value container.
func (*FormParameterGenerator) Source ¶
func (g *FormParameterGenerator) Source() definition.Source
Source returns the source generated by current generator.
type HTTPContext ¶
type HTTPContext interface { Request() *http.Request ResponseWriter() ResponseWriter ValueContainer() ValueContainer RoutePath() string SetRoutePath(path string) }
HTTPContext describes an http context.
func HTTPContextFrom ¶
func HTTPContextFrom(ctx context.Context) HTTPContext
HTTPContextFrom get http context from context.
type HTTPCtx ¶ added in v0.3.0
HTTPCtx contains a http.Request and a http.ResponseWriter for a request. It goes through the life cycle of a request.
func NewHTTPContext ¶ added in v0.3.0
func NewHTTPContext(resp http.ResponseWriter, request *http.Request) *HTTPCtx
NewHTTPContext generates the http context from ResponseWriter and Request.
func (*HTTPCtx) ResponseWriter ¶ added in v0.3.0
func (c *HTTPCtx) ResponseWriter() ResponseWriter
ResponseWriter gets ResponseWriter.
func (*HTTPCtx) RoutePath ¶ added in v0.3.0
RoutePath is the abstract path which matches request URL.
func (*HTTPCtx) SetRoutePath ¶ added in v0.3.0
SetRoutePath sets the abstract path which matches request URL.
func (*HTTPCtx) Value ¶ added in v0.3.0
func (c *HTTPCtx) Value(key interface{}) interface{}
Value returns itself when key is contextKeyUnderlyingHTTPContext.
func (*HTTPCtx) ValueContainer ¶ added in v0.3.0
func (c *HTTPCtx) ValueContainer() ValueContainer
ValueContainer gets ValueContainer.
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)
Generate generates an object by data from value container.
func (*HeaderParameterGenerator) Source ¶
func (g *HeaderParameterGenerator) Source() definition.Source
Source returns the source generated by current generator.
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.
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 (h *MetaDestinationHandler) Destination() definition.Destination
Destination returns definition.Destination which the destination handler can handle.
func (*MetaDestinationHandler) Handle ¶
func (h *MetaDestinationHandler) Handle(ctx context.Context, producers []Producer, code int, value interface{}) (goon bool, err error)
Handle handles a value. If the handler has something wrong, it should return an error.
func (*MetaDestinationHandler) Priority ¶
func (h *MetaDestinationHandler) Priority() int
Priority returns priority of the type handler.
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.
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)
Generate generates an object by data from value container.
func (*PathParameterGenerator) Source ¶
func (g *PathParameterGenerator) Source() definition.Source
Source returns the source generated by current generator.
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.
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)
Generate generates an object by data from value container.
func (*PrefabParameterGenerator) Source ¶
func (g *PrefabParameterGenerator) Source() definition.Source
Source returns the source generated by current generator.
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 ChooseProducer ¶ added in v0.3.0
ChooseProducer chooses the right producer.
func ProducerFor ¶
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)
Generate generates an object by data from value container.
func (*QueryParameterGenerator) Source ¶
func (g *QueryParameterGenerator) Source() definition.Source
Source returns the source generated by current generator.
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 // ResponseBody returns response body. ResponseBody() []byte // SetWrapRespBodyPolicy set wrap resp body policy. SetWrapRespBodyPolicy(bool) }
ResponseWriter extends http.ResponseWriter.
type Service ¶
Service handles HTTP requests.
Workflow:
Service.ServeHTTP() ---------------------- ↓ ↑
|-----Filters------| ↑
↓ ↑
|-Router/RPC Action 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.
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 { // Set sets path parameter key-value pairs. Set(key, value string) // Get gets path value. Get(key string) (string, bool) // 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.