Documentation ¶
Index ¶
- Constants
- Variables
- func AddActionCollectionRoute(router *httptreemux.ContextMux, basePath string, r CollectionActioner)
- func AddActionSingletonRoute(router *httptreemux.ContextMux, basePath string, r SingletonActioner)
- func AddCountCollectionRoute(router *httptreemux.ContextMux, basePath string, r CollectionCounter)
- func AddCreateCollectionRoute(router *httptreemux.ContextMux, basePath string, r CollectionCreator)
- func AddDeleteCollectionRoute(router *httptreemux.ContextMux, basePath string, r CollectionDeleter)
- func AddGetCollectionRoute(router *httptreemux.ContextMux, basePath string, r CollectionGetter)
- func AddGetSingletonRoute(router *httptreemux.ContextMux, basePath string, r SingletonGetter)
- func AddListCollectionRoute(router *httptreemux.ContextMux, basePath string, r CollectionLister)
- func AddUpdateCollectionRoute(router *httptreemux.ContextMux, basePath string, r CollectionUpdater)
- func AddUpdateSingletonRoute(router *httptreemux.ContextMux, basePath string, r SingletonUpdater)
- func ContextApiVersion(ctx context.Context) (apiVersion int)
- func ContextDetail(ctx context.Context, key interface{}) (value interface{})
- func ContextLogger(ctx context.Context) (logger *log.Logger)
- func ContextRequest(ctx context.Context) (request *http.Request)
- func ContextRequestId(ctx context.Context) (requestId string)
- func ContextRequestProgress(ctx context.Context) (reqProgress string)
- func ContextResponseHeaders(ctx context.Context) (header http.Header)
- func ContextSessionId(ctx context.Context) (sessionId string)
- func NewConfig(r io.Reader, cfg interface{}) error
- func NewNotImplementedResource() *notImplementedResource
- func NewStoppableTCPListener(addr string, keepalives bool) (net.Listener, error)
- func NewStoppableTLSListener(addr string, keepalives bool, certFile string, keyFile string) (net.Listener, error)
- func ReadConfig(path string, cfg interface{}) error
- func ReadRequest(req *http.Request, v interface{}) error
- func RegisterFormat(format string, mimeTypes []string)
- func RegisterTracerKind(name string, kind TracerKind)
- func RequestBearerToken(r *http.Request) string
- func RequestExternalHost(r *http.Request) string
- func RequestNextLink(r *http.Request, cursor string) *url.URL
- func RequestPageSize(r *http.Request) (pageSize int)
- func RequestQueryCursor(r *http.Request) string
- func RequestResourceNonce(r *http.Request) string
- func SetContextCallerId(ctx context.Context, callerId string)
- func SetContextDetail(ctx context.Context, key, value interface{})
- func SetContextRequestProgress(ctx context.Context, progress string)
- func SetContextSkipInfoLog(ctx context.Context)
- func TestDispatch(rw http.ResponseWriter, req *http.Request, h http.Handler)
- func WriteResponse(rw http.ResponseWriter, status int, v interface{}) (err error)
- type CollectionActioner
- type CollectionCounter
- type CollectionCreator
- type CollectionDeleter
- type CollectionGetter
- type CollectionLister
- type CollectionUpdater
- type Error
- type Handler
- type HandlerFunc
- type ListenerStoppedError
- type ResponseWriter
- type Service
- func (s *Service) AccessLogger() *log.Logger
- func (s *Service) AddHandler(h Handler)
- func (s *Service) AddResource(version int, basePath string, r interface{}) error
- func (s *Service) AppendHandler(h Handler)
- func (s *Service) Config() *ServiceConfig
- func (s *Service) Logger() *log.Logger
- func (s *Service) PrependHandler(h Handler)
- func (s *Service) Router(version int) (*httptreemux.ContextMux, error)
- func (s *Service) Run() error
- func (s *Service) SetSchemas(schemas http.FileSystem)
- func (s *Service) Tracer() opentracing.Tracer
- type ServiceConfig
- type ServiceConfigExt
- type SingletonActioner
- type SingletonGetter
- type SingletonUpdater
- type StoppableTCPListener
- type TracerKind
Constants ¶
const ( ContentTypeCss = "text/css" ContentTypeCsv = "text/csv" ContentTypeGif = "image/gif" ContentTypeGrpc = "application/grpc" ContentTypeHtml = "text/html" ContentTypeJson = "application/json" ContentTypeMsgpack = "application/msgpack" ContentTypeMultipartFormData = "multipart/form-data" ContentTypeOctetStream = "application/octet-stream" ContentTypePlain = "text/plain" ContentTypePng = "image/png" ContentTypeProtobuf = "application/protobuf" ContentTypeWwwFormUrlencoded = "application/x-www-form-urlencoded" ContentTypeXml = "application/xml" )
const ( EcodeUnknown = "UNKNOWN_ERROR" EcodeInternal = "INTERNAL_ERROR" EcodeUnsupportedMediaType = "UNSUPPORTED_MEDIA_TYPE" EcodeSerializationFailed = "SERIALIZATION_FAILED" EcodeDeserializationFailed = "DESERIALIZATION_FAILED" EcodeResourceIdMismatch = "RESOURCE_ID_MISMATCH" EcodeApiVersionInvalid = "API_VERSION_INVALID" EcodeApiVersionTooOld = "API_VERSION_TOO_OLD" EcodeApiVersionTooNew = "API_VERSION_TOO_NEW" EcodeValidationFailed = "VALIDATION_FAILED" EcodeLocked = "LOCKED" EcodeUpdatePreempted = "UPDATE_PREEMPTED" EcodeInvalidViewName = "INVALID_VIEW_NAME" EcodeMissingViewParameter = "MISSING_VIEW_PARAMETER" EcodeInvalidViewParameter = "INVALID_VIEW_PARAMETER" EcodeInvalidParameterValue = "INVALID_PARAMETER_VALUE" )
const ( HeaderAccept = "Accept" HeaderAcceptEncoding = "Accept-Encoding" HeaderAuthorization = "Authorization" HeaderCacheControl = "Cache-Control" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLength = "Content-Length" HeaderContentType = "Content-Type" HeaderETag = "ETag" HeaderExpect = "Expect" HeaderForwardedFor = "X-Forwarded-For" HeaderForwardedHost = "X-Forwarded-Host" HeaderIfNoneMatch = "If-None-Match" HeaderLocation = "Location" HeaderRequestId = "X-Request-Id" HeaderSessionId = "X-Session-Id" HeaderSpirentApiVersion = "X-Spirent-Api-Version" HeaderSpirentInhibitResponse = "X-Spirent-Inhibit-Response" HeaderSpirentNextLink = "X-Spirent-Next-Link" HeaderSpirentPageSize = "X-Spirent-Page-Size" HeaderSpirentResourceNonce = "X-Spirent-Resource-Nonce" HeaderUserAgent = "User-Agent" )
const ( RouteTagSeg1 = "seg1" RouteTagSeg2 = "seg2" RouteParamAction = RouteTagSeg2 // e.g. in `POST /resource/id/action` RouteParamId = RouteTagSeg1 // e.g. in `GET /resource/id` )
Variables ¶
var ( // ErrInvalidMinApiVersion occurs when a service's minimum API version is <= 0. ErrInvalidMinApiVersion = errors.New("service's minimum API version must be greater than zero") // ErrInvalidMaxApiVersion occurs when a service's maximum API version is <= 0. ErrInvalidMaxApiVersion = errors.New("service's maximum API version must be greater than zero") // ErrMismatchedApiVersions occurs when a service's minimum API version > its maximum API version. ErrMismatchedApiVersions = errors.New("service's maximum API version must be greater than or equal to the minimum API version") )
var FormDecoder = schema.NewDecoder()
Functions ¶
func AddActionCollectionRoute ¶
func AddActionCollectionRoute(router *httptreemux.ContextMux, basePath string, r CollectionActioner)
AddActionCollectionRoute adds a route for a CollectionActioner.
func AddActionSingletonRoute ¶
func AddActionSingletonRoute(router *httptreemux.ContextMux, basePath string, r SingletonActioner)
AddActionSingletonRoute adds a route for a SingletonActioner.
func AddCountCollectionRoute ¶
func AddCountCollectionRoute(router *httptreemux.ContextMux, basePath string, r CollectionCounter)
AddCountCollectionRoute adds a route for a CollectionCounter.
func AddCreateCollectionRoute ¶
func AddCreateCollectionRoute(router *httptreemux.ContextMux, basePath string, r CollectionCreator)
AddCreateCollectionRoute adds a route for a CollectionCreator.
func AddDeleteCollectionRoute ¶
func AddDeleteCollectionRoute(router *httptreemux.ContextMux, basePath string, r CollectionDeleter)
AddDeleteCollectionRoute adds routes for a CollectionDeleter.
func AddGetCollectionRoute ¶
func AddGetCollectionRoute(router *httptreemux.ContextMux, basePath string, r CollectionGetter)
AddGetCollectionRoute adds a route for a CollectionGetter.
func AddGetSingletonRoute ¶
func AddGetSingletonRoute(router *httptreemux.ContextMux, basePath string, r SingletonGetter)
AddGetSingletonRoute adds a route for a SingletonGetter.
func AddListCollectionRoute ¶
func AddListCollectionRoute(router *httptreemux.ContextMux, basePath string, r CollectionLister)
AddListCollectionRoute adds a route for a CollectionLister.
func AddUpdateCollectionRoute ¶
func AddUpdateCollectionRoute(router *httptreemux.ContextMux, basePath string, r CollectionUpdater)
AddUpdateCollectionRoute adds a route for a CollectionUpdater.
func AddUpdateSingletonRoute ¶
func AddUpdateSingletonRoute(router *httptreemux.ContextMux, basePath string, r SingletonUpdater)
AddUpdateSingletonRoute adds a route for a SingletonUpdater.
func ContextApiVersion ¶
ContextApiVersion returns the current HTTP request's API version value from a context.Context, if possible.
func ContextDetail ¶
ContextDetail gets a detail from the current HTTP request's context, if possible.
func ContextLogger ¶
ContextLogger returns the Service's logger instance value from a context.Context, if possible.
func ContextRequest ¶
ContextRequest returns the current HTTP request from a context.Context, if possible.
func ContextRequestId ¶
ContextRequestId returns the current HTTP request's ID value from a context.Context, if possible.
func ContextRequestProgress ¶
ContextRequestProgress returns the current HTTP request's progress trace from a context.Context, if possible.
func ContextResponseHeaders ¶
ContextResponseHeaders returns the current HTTP response's header collection from a context.Context, if possible.
func ContextSessionId ¶
ContextSessionId returns the current HTTP request's session ID value from a context.Context, if possible.
func NewConfig ¶
NewConfig parses a YAML config file from an io.Reader. The file is strictly parsed (any fields that are found in the data that do not have corresponding struct members, or mapping keys that are duplicates, will result in an error) into the struct pointed to by cfg.
func NewNotImplementedResource ¶ added in v3.0.6
func NewNotImplementedResource() *notImplementedResource
func NewStoppableTCPListener ¶
func NewStoppableTLSListener ¶
func ReadConfig ¶
ReadConfig reads a YAML config file from path. The file is strictly parsed (any fields that are found in the data that do not have corresponding struct members, or mapping keys that are duplicates, will result in an error) into the struct pointed to by cfg.
func ReadRequest ¶
ReadRequest deserializes a request body according to the Content-Type header.
func RegisterFormat ¶
RegisterFormat registers a new format and associated MIME types.
func RegisterTracerKind ¶
func RegisterTracerKind(name string, kind TracerKind)
func RequestBearerToken ¶
RequestBearerToken returns the bearer token from an http.Request Authorization header. If the header isn't present or it doesn't start with the string "Bearer", then an empty string is returned.
func RequestExternalHost ¶
RequestExternalHost returns the best estimation of the service's host name. If a reverse proxy forwarded the request and populated the X-Forwarded-Host header, then that value is returned. Otherwise, the Host member from the http.Request is returned.
func RequestNextLink ¶
RequestNextLink returns a url.URL value suitable for use in a response header as the X-Spirent-Next-Link value. It combines the current http.Request URI together with a "next page" cursor value.
func RequestPageSize ¶
RequestPageSize returns the client's requested page size, defaulting to math.MaxInt32 in cases where the X-Spirent-Page-Size header wasn't included in the original request or when the header's value is <= 0.
func RequestQueryCursor ¶
RequestQueryCursor returns the "cursor" query string value from the http.Request.
func RequestResourceNonce ¶
RequestResourceNonce returns the X-Spirent-Resource-Nonce header value from the http.Request.
func SetContextCallerId ¶
SetCallerId sets a service-specific caller id string in a context.Context. If set, this caller id will appear in the request's access log entry and trace data.
func SetContextDetail ¶
SetContextDetail sets a detail in the current HTTP request's context. This may be used by the service's own middleware and avoids allocating a new request with additional context.
func SetContextRequestProgress ¶
SetContextRequestProgress sets the current HTTP request's progress trace in a context.Context.
func SetContextSkipInfoLog ¶ added in v3.0.5
SetContextSkipInfoLog sets a request-specific flag in a context.Context. If set, the request's access log entry and trace data will be skipped at InfoLevel if request was successful. Errors will always be logged.
func TestDispatch ¶
TestDispatch allows external code to test its own handlers, complete with mocked luddite handler details.
func WriteResponse ¶
func WriteResponse(rw http.ResponseWriter, status int, v interface{}) (err error)
WriteResponse serializes a response body according to the negotiated Content-Type.
Types ¶
type CollectionActioner ¶
type CollectionActioner interface { // Action returns an HTTP status code and a response body (or error). Action(req *http.Request, id string, action string) (int, interface{}) }
CollectionActioner is a collection-style resource that executes an action in response to `POST /resource/id/action`.
type CollectionCounter ¶
type CollectionCounter interface { // Count returns an HTTP status code and a count of resources (or error). Count(req *http.Request) (int, interface{}) }
CollectionCounter is a collection-style resource that returns a count of its elements in response to `GET /resource/all/count`.
type CollectionCreator ¶
type CollectionCreator interface { // New returns a new instance of the resource. New() interface{} // Id returns a resource's identifier as a string. Id(value interface{}) string // Create returns an HTTP status code and a new resource (or error). Create(req *http.Request, value interface{}) (int, interface{}) }
CollectionCreator is a collection-style resource that creates a new element in response to `POST /resource`.
type CollectionDeleter ¶
type CollectionDeleter interface { // Delete returns an HTTP status code and a deleted resource (or error). Delete(req *http.Request, id string) (int, interface{}) }
CollectionDeleter is a collection-style resource that deletes a specific element in response to `DELETE /resource/id`. It may also optionally delete the entire collection in response to `DELETE /resource`.
type CollectionGetter ¶
type CollectionGetter interface { // Get returns an HTTP status code and a single resource (or error). Get(req *http.Request, id string) (int, interface{}) }
CollectionGetter is a collection-style resource that returns a specific element in response to `GET /resource/id`.
type CollectionLister ¶
type CollectionLister interface { // List returns an HTTP status code and a slice of resources (or error). List(req *http.Request) (int, interface{}) }
CollectionLister is a collection-style resource that returns all its elements in response to `GET /resource`.
type CollectionUpdater ¶
type CollectionUpdater interface { // New returns a new instance of the resource. New() interface{} // Id returns a resource's identifier as a string. Id(value interface{}) string // Update returns an HTTP status code and an updated resource (or error). Update(req *http.Request, id string, value interface{}) (int, interface{}) }
CollectionUpdater is a collection-style resource that updates a specific element in response to `PUT /resource/id`.
type Error ¶
type Error struct { XMLName xml.Name `json:"-" xml:"error"` Code string `json:"code" xml:"code"` Message string `json:"message" xml:"message"` Stack string `json:"stack,omitempty" xml:"stack,omitempty"` }
Error is a transfer object that is serialized as the body in 4xx and 5xx responses.
type Handler ¶
type Handler interface {
ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)
}
Handler is an interface that objects can implement to be registered to serve as middleware in a Service's middleware stack. ServeHTTP should yield to the next middleware in the chain by invoking the next http.HandlerFunc passed in.
If the Handler writes to the ResponseWriter, the next http.HandlerFunc should not be invoked.
func WrapHTTPHandler ¶
WrapHTTPHandler converts an http.Handler into a Handler.
func WrapHTTPHandlerFunc ¶
func WrapHTTPHandlerFunc(f http.HandlerFunc) Handler
WrapHTTPHandlerFunc converts an http.HandlerFunc into a Handler.
type HandlerFunc ¶
type HandlerFunc func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)
HandlerFunc is an adapter to allow the use of ordinary functions as middleware handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler object that calls f.
func (HandlerFunc) ServeHTTP ¶
func (h HandlerFunc) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)
type ListenerStoppedError ¶
type ListenerStoppedError struct{}
func (*ListenerStoppedError) Error ¶
func (e *ListenerStoppedError) Error() string
type ResponseWriter ¶
type ResponseWriter interface { http.ResponseWriter http.Flusher http.Hijacker // Written returns true once the ResponseWriter has been written. Written() bool // Status returns the status code of the response or 0 if the // response has not been written. Status() int // Size returns the size of the response body or 0 if the response has // not been written. Size() int64 }
ResponseWriter is a wrapper around http.ResponseWriter that provides extra information about the response.
func ContextResponseWriter ¶
func ContextResponseWriter(ctx context.Context) (rw ResponseWriter)
ContextResponseWriter returns the current HTTP request's ResponseWriter from a context.Context, if possible.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service implements a standalone RESTful web service.
func ContextService ¶
ContextService returns the Service instance value from a context.Context, if possible.
func NewService ¶
func NewService(config *ServiceConfig, configExt ...*ServiceConfigExt) (*Service, error)
NewService creates a new Service instance based on the given config. Middleware handlers and resources should be added before the service is run. The service may be run one time.
func (*Service) AccessLogger ¶ added in v3.0.3
Logger returns the service's access logger instance.
func (*Service) AddHandler ¶
AddHandler forwards to AppendHandler. It is provided for backward compatibility.
func (*Service) AddResource ¶
AddResource is a convenience method that performs runtime type assertions on a resource handler and adds routes as appropriate based on what interfaces are implemented. The same effect can be achieved by calling the various "Add*CollectionResource" and "Add*SingletonResource" functions with the appropriate router instance.
func (*Service) AppendHandler ¶
AppendHandler appends a middleware handler to the service's middleware stack. All handlers must be added before Run is called.
func (*Service) Config ¶
func (s *Service) Config() *ServiceConfig
Config returns the service's ServiceConfig instance.
func (*Service) PrependHandler ¶
PrependHandler prepends a middleware handler to the service's middleware stack. All handlers must be added before Run is called.
func (*Service) Router ¶
func (s *Service) Router(version int) (*httptreemux.ContextMux, error)
Router returns the service's router instance for the given API version.
func (*Service) Run ¶
Run starts the service's HTTP server and runs it forever or until SIGINT is received. This method should be invoked once per service.
func (*Service) SetSchemas ¶
func (s *Service) SetSchemas(schemas http.FileSystem)
SetSchemas allows a service to provide its own HTTP filesystem to be used for schema assets. This overrides the use of the local filesystem and paths given in the service config.
func (*Service) Tracer ¶
func (s *Service) Tracer() opentracing.Tracer
Tracer returns the service's opentracing.Tracer instance.
type ServiceConfig ¶
type ServiceConfig struct { // Addr is the address:port pair that the HTTP server listens on. Addr string // Prefix is a prefix to add to every path Prefix string CORS struct { // Enabled, when true, enables CORS. Enabled bool // AllowedOrigins contains the list of origins a cross-domain request can be executed from. Defaults to "*" on an empty list. AllowedOrigins []string `yaml:"allowed_origins"` // AllowedMethods contains the list of methods the client is allowed to use with cross-domain requests. Defaults to "GET", "POST", "PUT" and "DELETE" on an empty list. AllowedMethods []string `yaml:"allowed_methods"` // AllowedHeaders contains the list of non-simple headers clients are allowed to use in cross-origin requests. An empty list is interpreted literally however "Origin" is always appended. AllowedHeaders []string `yaml:"allowed_headers"` // ExposedHeaders contains the list of non-simple headers clients are allowed to access in cross-origin responses. An empty list is interpreted literally. ExposedHeaders []string `yaml:"exposed_headers"` // AllowCredentials indicates whether the request can include user credentials like cookies or HTTP auth. AllowCredentials bool `yaml:"allow_credentials"` } // Credentials is a generic map of strings that may be used to store tokens, AWS keys, etc. Credentials map[string]string Debug struct { // Stacks, when true, causes stack traces to appear in 500 error responses. Stacks bool } Log struct { // ServiceLogPath sets the file path for the service log (written as JSON). If unset, defaults to stdout (written as text). ServiceLogPath string `yaml:"service_log_path"` // ServiceLogLevel sets the minimum log level for the service log, If unset, defaults to INFO. ServiceLogLevel string `yaml:"service_log_level"` // AccessLogPath sets the file path for the access log (written as JSON). If unset, defaults to stdout (written as text). AccessLogPath string `yaml:"access_log_path"` } Metrics struct { // Enabled, when true, enables the service's prometheus client. Enabled bool // UriPath sets the metrics path. Defaults to "/metrics". URIPath string `yaml:"uri_path"` } Profiler struct { // Enabled, when true, enables the service's profiling endpoints. Enabled bool // UriPath sets the profiler path. Defaults to "/debug/pprof". URIPath string `yaml:"uri_path"` } Schema struct { // Enabled, when true, self-serve the service's own schema. Enabled bool // URIPath sets the URI path for the schema. URIPath string `yaml:"uri_path"` // FilePath sets the base file path for the schema. FilePath string `yaml:"file_path"` // FileName sets the schema file name. FileName string `yaml:"file_name"` // RootRedirect, when true, redirects the service's root to the default schema. RootRedirect bool `yaml:"root_redirect"` } Trace struct { // Enabled, when true, enables distributed tracing using the // OpenTracing framework. Enabled bool // Tracer selects the tracer implementation. Built-in // Tracer: json, yaml. Tracer string // Params is a map of tracer-specific parameters. Params map[string]string } Transport struct { // Tls, when true, causes the service to listen using HTTPS. TLS bool `yaml:"tls"` // CertFilePath sets the path to the server's certificate file. CertFilePath string `yaml:"cert_file_path"` // KeyFilePath sets the path to the server's key file. KeyFilePath string `yaml:"key_file_path"` } Version struct { // Min sets the minimum API version that the service supports. Min int // Max sets the maximum API version that the service supports. Max int } }
ServiceConfig holds a service's config values.
func (*ServiceConfig) Normalize ¶
func (config *ServiceConfig) Normalize()
Normalize applies sensible defaults to service config values when they are otherwise unspecified or invalid.
func (*ServiceConfig) Validate ¶
func (config *ServiceConfig) Validate() error
Validate sanity-checks service config values.
type ServiceConfigExt ¶ added in v3.0.3
ServiceConfigExt holds custom extensions to a service's config.
type SingletonActioner ¶
type SingletonActioner interface { // Action returns an HTTP status code and a response body (or error). Action(req *http.Request, action string) (int, interface{}) }
SingletonActioner is a singleton-style resource that executes an action in response to `POST /resource/action`.
type SingletonGetter ¶
type SingletonGetter interface { // Get returns an HTTP status code and a single resource (or error). Get(req *http.Request) (int, interface{}) }
SingletonGetter is a singleton-style resource that returns a response to `GET /resource`.
type SingletonUpdater ¶
type SingletonUpdater interface { // New returns a new instance of the resource. New() interface{} // Update returns an HTTP status code and an updated resource (or error). Update(req *http.Request, value interface{}) (int, interface{}) }
SingletonUpdater is a singleton-style resource that is updated in response to `PUT /resource`.
type StoppableTCPListener ¶
type StoppableTCPListener struct { *net.TCPListener // contains filtered or unexported fields }
type TracerKind ¶
type TracerKind interface { // New constructs a concrete opentracing.Tracer implementation, given a // map of tracer-specific parameters. New(params map[string]string, logger *log.Logger) (opentracing.Tracer, error) // TraceId returns a span's trace id. TraceId(span opentracing.Span) uint64 // IsNoop returns true when the tracer is a no-op tracer. This may be // useful for short-circuiting span tagging and logging. IsNoop() bool }