service

package
v0.1.0-alpha.0 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2018 License: Apache-2.0 Imports: 20 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

This section is empty.

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 ConvertToFloat32

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

ConvertToFloat32 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 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 ConvertToInt32

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

ConvertToInt32 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 ConvertToInt8

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

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

func ConvertToString

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

ConvertToString return the first element in []string.

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 ConvertToUint32

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

ConvertToUint32 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 ConvertToUint8

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

ConvertToUint8 converts []string to uint8. 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 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 WarpHTTPHandler

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

WarpHTTPHandler warps a http handler to definition function.

func WarpHTTPHandlerFunc

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

WarpHTTPHandlerFunc warps a 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 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 {
	// SetLogger sets logger to server.
	SetLogger(logger log.Logger)
	// SetModifier sets definition modifier.
	SetModifier(m DefinitionModifier)
	// AddFilters add filters to filter requests.
	AddFilter(filters ...Filter)
	// AddDescriptors adds descriptors to router.
	AddDescriptor(descriptors ...definition.Descriptor) error
	// 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 ConsumeAllIfComsumesIsEmpty

func ConsumeAllIfComsumesIsEmpty() DefinitionModifier

ConsumeAllIfComsumesIsEmpty 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 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
}

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{}

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 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 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{}

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
y or Y : Canonical URL