rest

package
v2.0.2 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2022 License: Apache-2.0 Imports: 22 Imported by: 20

Documentation

Overview

A basic REST server supporting HTTP.

This package implements a HTTP server using net/http and github.com/gorilla/mux taking away most of the required boiler plate code usually needed when implementing basic REST services. It also provides many utility methods for handling both JSON and XML responses.

A basic REST server supporting HTTP.

This package implements a HTTP server using net/http and github.com/gorilla/mux taking away most of the required boiler plate code usually needed when implementing basic REST services. It also provides many utility methods for handling both JSON and XML responses.

Package rest A basic REST server supporting HTTP.

This package implements a HTTP server using net/http and github.com/gorilla/mux taking away most of the required boiler plate code usually needed when implementing basic REST services. It also provides many utility methods for handling both JSON and XML responses.

Index

Constants

View Source
const (
	APPLICATION_JSON string = "application/json"
	APPLICATION_XML  string = "application/xml"
	TEXT_JSON        string = "text/json"
	TEXT_HTML        string = "text/html"
	TEXT_XML         string = "text/xml"
)

Variables

This section is empty.

Functions

func ConsoleLogger

func ConsoleLogger() mux.MiddlewareFunc

ConsoleLogger returns a middleware function to log requests to the console

func DefaultIDGenerator

func DefaultIDGenerator() (string, error)

Default ID generator, Generates a UUID

func FormatLogger

func FormatLogger(f FormatLoggerFunc) mux.MiddlewareFunc

FormatLogger returns a middleware function to log requests to a function. Note: The format passed to this function will not have a trailing "\n" nor will it have any time information in it.

func Handler

func Handler(f func(*Rest) error) func(w http.ResponseWriter, r *http.Request)

Handler creates a wrapper around a rest handler and one used by mux

func LogLogger

func LogLogger(l *log.Logger) mux.MiddlewareFunc

LogLogger returns a middleware function to log requests to a specific logger

func RequestID

func RequestID(nextRequestID IdGenerator) mux.MiddlewareFunc

RequestID adds request tracing by adding the "X-Request-Id" header to the response

func TraceRequest

func TraceRequest(header string, nextRequestID IdGenerator) mux.MiddlewareFunc

TraceRequest adds a request tracking header, similar to X-Request-ID or X-Amz-Request-Id used by AmazonS3.

header the Header name nextRequestID function to generate the new id

Types

type AddHeadersDecorator

type AddHeadersDecorator map[string]string

AddHeadersDecorator is a decorator which ensures that the given headers are always present in a response that has not returned an error.

Here's an example on ensuring certain headers are always present:

Decorate( (&rest.AddHeadersDecorator{
  "Access-Control-Allow-Origin": "*",
  "X-Clacks-Overhead": "GNU Terry Pratchett",
}).Decorator )

func (*AddHeadersDecorator) Decorator

type FormatLoggerFunc

type FormatLoggerFunc func(string, ...interface{})

type IdGenerator

type IdGenerator func() (string, error)

An ID Generator

type Rest

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

A Rest query. This struct handles everything from the inbound request and sending the response

func GetRest

func GetRest(ctx context.Context) *Rest

GetRest returns the *Rest instance from a Context issued with the Do() function.

func NewRest

func NewRest(writer http.ResponseWriter, request *http.Request) *Rest

NewRest creates a new Rest query

func (*Rest) AccessControlAllowOrigin

func (r *Rest) AccessControlAllowOrigin(value string) *Rest

func (*Rest) AddHeader

func (r *Rest) AddHeader(name string, value string) *Rest

AddHeader adds a header to the response, replacing any existing entry

func (*Rest) Body

func (r *Rest) Body(v interface{}) error

Body decodes the request body into an interface. If the body is compressed with Content-Encoding header set to "gzip" then the body is decoded first. If the Content-Type is "text/xml" or "application/xml" then the body is presumed to be in XML, otherwise json is presumed.

func (*Rest) BodyReader

func (r *Rest) BodyReader() (io.ReadCloser, error)

BodyReader() returns Request().Body unless the Content-Encoding header is set to gzip in which case the body is decompressed before calling the reader

func (*Rest) CacheControl

func (r *Rest) CacheControl(cache int) *Rest

CacheControl manages the Cache-Control header in the response. cache < 0 for "no cache", cache = 0 to ignore (i.e. dont set the header) cache > 0 Time in seconds for the client to cache the response

func (*Rest) CacheMaxAge

func (r *Rest) CacheMaxAge(age int) *Rest

func (*Rest) CacheNoCache

func (r *Rest) CacheNoCache() *Rest

func (*Rest) ContentType

func (r *Rest) ContentType(c string) *Rest

Value sets the response value

func (*Rest) Context

func (r *Rest) Context() string

Context returns the base context for this request

func (*Rest) Etag

func (r *Rest) Etag(tag string) *Rest

func (*Rest) GetAttribute

func (r *Rest) GetAttribute(name string) (interface{}, bool)

GetAttribute returns the named request attribute

func (*Rest) GetHeader

func (r *Rest) GetHeader(name string) string

GetHeader returns a header from the request or "" if not present

func (*Rest) HTML

func (r *Rest) HTML() *Rest

HTML forces the response to be html

func (*Rest) JSON

func (r *Rest) JSON() *Rest

JSON forces the response to be JSON

func (*Rest) Push

func (r *Rest) Push(target string, opts *http.PushOptions) error

Push initiates an HTTP/2 server push. This constructs a synthetic request using the given target and options, serializes that request into a PUSH_PROMISE frame, then dispatches that request using the server's request handler. If opts is nil, default options are used.

The target must either be an absolute path (like "/path") or an absolute URL that contains a valid host and the same scheme as the parent request. If the target is a path, it will inherit the scheme and host of the parent request.

The HTTP/2 spec disallows recursive pushes and cross-authority pushes. Push may or may not detect these invalid pushes; however, invalid pushes will be detected and canceled by conforming clients.

Handlers that wish to push URL X should call Push before sending any data that may trigger a request for URL X. This avoids a race where the client issues requests for X before receiving the PUSH_PROMISE for X.

Push returns ErrNotSupported if the client has disabled push or if push is not supported on the underlying connection.

func (*Rest) PushSupported

func (r *Rest) PushSupported() bool

PushSupported returns true if http2 Push is supported

func (*Rest) Reader

func (r *Rest) Reader(rdr io.Reader) *Rest

Value sets the response value

func (*Rest) Request

func (r *Rest) Request() *http.Request

Request return the underlying http.Request so that

func (*Rest) Self

func (r *Rest) Self(path string) string

Self returns the full request uri based on the headers of the request and the supplied path.

func (*Rest) SelfRequest

func (r *Rest) SelfRequest() string

SelfRequest returns the full request uri based on the headers of the request and the RequestURI

func (*Rest) Send

func (r *Rest) Send() error

Send returns data to the client. If the request has the Accept header of "text/xml" or "application/xml" then the response will be in XML, otherwise in JSON.

func (*Rest) SetAttribute

func (r *Rest) SetAttribute(n string, v interface{})

SetAttribute returns the named request attribute

func (*Rest) SetDate

func (r *Rest) SetDate(name string, t int64) *Rest

SetUnixDate Sets Date header to a unix timestamp

func (*Rest) SetUnixDate

func (r *Rest) SetUnixDate(t int64) *Rest

SetUnixDate Sets Date header to a unix timestamp

func (*Rest) Status

func (r *Rest) Status(status int) *Rest

Status sets the HTTP status of the response.

func (*Rest) Value

func (r *Rest) Value(value interface{}) *Rest

Value sets the response value

func (*Rest) Var

func (r *Rest) Var(name string) string

Var returns the named route variable or "" if none

func (*Rest) VarInt

func (r *Rest) VarInt(name string, def int) int

func (*Rest) Writer

func (r *Rest) Writer() io.Writer

Writer returns a io.Writer to write the response

func (*Rest) XML

func (r *Rest) XML() *Rest

XML forces the response to be XML

type RestBuilder

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

RestBuilder allows for a Rest endpoint to be built

func (*RestBuilder) Authenticator

func (r *RestBuilder) Authenticator(f RestDecorator) *RestBuilder

Authenticator is a RestDecorator which is specific to the current endpoint being built. It's called Authenticator as it's usually used for authentication but it can be used for other purposes.

func (*RestBuilder) Build

func (r *RestBuilder) Build() *RestBuilder

Build a rest endpoint

func (*RestBuilder) Decorate

func (r *RestBuilder) Decorate(f RestDecorator) *RestBuilder

Decorate will invoke a RestDecorator against the RestHandler set by Handler() to decorate it. This is usually used to add error handling, ensuring certain headers are in the response etc. Note: This decorator will be used by all endpoints built by this instance of the builder. To apply a decorator on a single endpoint use Authenticator()

func (*RestBuilder) Handler

func (r *RestBuilder) Handler(f RestHandler) *RestBuilder

Handler sets the RestHandler to use for this endpoint

func (*RestBuilder) Headers

func (r *RestBuilder) Headers(s ...string) *RestBuilder

Headers adds a matcher for request header values. It accepts a sequence of key/value pairs to be matched. For example:

r := server.RestBuilder()
r.Headers("Content-Type", "application/json",
          "X-Requested-With", "XMLHttpRequest")

The above route will only match if both request header values match. If the value is an empty string, it will match any value if the key is set.

func (*RestBuilder) HeadersRegexp

func (r *RestBuilder) HeadersRegexp(s ...string) *RestBuilder

HeadersRegexp accepts a sequence of key/value pairs, where the value has regex support. For example:

r := server.RestBuilder()
r.HeadersRegexp("Content-Type", "application/(text|json)",
          "X-Requested-With", "XMLHttpRequest")

The above route will only match if both the request header matches both regular expressions. If the value is an empty string, it will match any value if the key is set. Use the start and end of string anchors (^ and $) to match an exact value.

func (*RestBuilder) Method

func (r *RestBuilder) Method(s ...string) *RestBuilder

Method sets the HTTP Method this endpoint is to use

func (*RestBuilder) Path

func (r *RestBuilder) Path(s ...string) *RestBuilder

Pattern adds a path to the end point being built. You can provide multiple patterns for the call being built

func (*RestBuilder) PathPrefix

func (r *RestBuilder) PathPrefix(pathPrefix string) *RestBuilder

PathPrefix is the common prefix that will be prepended to all endpoints in this builder.

It's preferable if a group of endpoints share the same contant prefix, e.g. "/api" to use this not just to save typing the same prefix as this will improve performance during matching.

Any trailing "/" are removed.

If the prefix does not start with a "/" then one is prepended.

"" or "/" are treated as no prefix.

func (*RestBuilder) Queries

func (r *RestBuilder) Queries(s ...string) *RestBuilder

Queries adds a matcher for URL query values. It accepts a sequence of key/value pairs. Values may define variables. For example:

r := server.RestBuilder()
r.Queries("foo", "bar", "id", "{id:[0-9]+}")

The above route will only match if the URL contains the defined queries values, e.g.: ?foo=bar&id=42.

It the value is an empty string, it will match any value if the key is set.

Variables can define an optional regexp pattern to be matched:

- {name} matches anything until the next slash.

- {name:pattern} matches the given regexp pattern.

func (*RestBuilder) Reset

func (r *RestBuilder) Reset() *RestBuilder

Reset() resets the builder so only the common entries are used in the next Build(), e.g. Decorator()'s' and PathPrefix() are affected by this.

Note, Build() call this so it's not normally required

type RestDecorator

type RestDecorator func(RestHandler) RestHandler

A decorator decorating a RestHandler

type RestHandler

type RestHandler func(*Rest) error

A handler of a rest call

type Server

type Server struct {
	Headers []string // The permitted headers
	Origins []string // The permitted Origins
	Methods []string // The permitted methods
	Address string   // Address to bind to, "" for any
	NoFlags bool     // true to disable command line flags
	Port    int      // Port to listen to
	// contains filtered or unexported fields
}

Server The internal config of a Server

func (*Server) Do

func (s *Server) Do(path string, f func(ctx context.Context) error) *mux.Route

Do uses a func(Context) style handler for the given path.

func (*Server) Get

func (s *Server) Get(name string) *mux.Route

Get returns a named route. You can name a Route by calling Name(name string) against the route returned by either Handle or HandleFunc

func (*Server) Handle

func (s *Server) Handle(path string, f func(*Rest) error) *mux.Route

Handle registers a new route with a matcher for the URL path. Unlike HandleFunc() this accepts a func that just takes a Rest instance. If the returned error is not nil then a 500 response is issued otherwise the response is sent unless Rest.Send() has already been called.

func (*Server) HandleFunc

func (s *Server) HandleFunc(path string, f func(http.ResponseWriter, *http.Request)) *mux.Route

HandleFunc registers a new route with a matcher for the URL path

func (*Server) Init

func (s *Server) Init(_ *kernel.Kernel) error

func (*Server) NotFound

func (s *Server) NotFound(f func(*Rest) error)

NotFound Adds a custom NotFound handler

func (*Server) PostInit

func (s *Server) PostInit() error

func (*Server) RestBuilder

func (s *Server) RestBuilder() *RestBuilder

Begin building rest endpoints on a server

func (*Server) Run

func (s *Server) Run() error

func (*Server) Static

func (s *Server) Static(prefix, dir string)

Static adds a static file service at a specific prefix. prefix is the prefix to serve from, e.g. "/static/" dir is the directory to serve static content from

func (*Server) Use

func (s *Server) Use(handler mux.MiddlewareFunc)

Use adds a MiddlewareHandler to the server. E.g. server.Use( ConsoleLogger )

type ServerContext

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

func (*ServerContext) Context

func (c *ServerContext) Context(context string) *ServerContext

Context creates a new ServerContext based on the current instance. The new Context will be the existing one suffixed with the new one. This allows for further grouping of rest services.

func (*ServerContext) Get

func (c *ServerContext) Get(name string) *mux.Route

Get returns a named route. You can name a Route by calling Name(name string) against the route returned by either Handle or HandleFunc

func (*ServerContext) Handle

func (c *ServerContext) Handle(path string, f func(*Rest) error) *mux.Route

Handle registers a new route with a matcher for the URL path based on the underlying ServerContext.

func (*ServerContext) HandleFunc

func (c *ServerContext) HandleFunc(path string, f func(http.ResponseWriter, *http.Request)) *mux.Route

HandleFunc registers a new route with a matcher for the URL path

type StatusCodeResponseWriter

type StatusCodeResponseWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

StatusCodeResponseWriter is an implementation of http.ResponseWriter which can be used to obtain the response status code.

Example:

func handler(w http.ResponseWriter, r *http.Request) {
  rw := &StatusCodeResponseWriter{}
  ServeHTTP( rw.Wrap( w ), r )
  statusCode := rw.GetStatus()
}

The Wrap() function returns a http.ResponseWriter with supports the http.Flusher or http.Pusher interfaces if the one being wrapped supports it.

func (*StatusCodeResponseWriter) GetStatus

func (rw *StatusCodeResponseWriter) GetStatus() int

GetStatus returns the staus code of the response

func (*StatusCodeResponseWriter) Wrap

Wrap wraps an existing http.ResponseWriter to our instance. If the wrapped instance implements the http.Flusher or http.Pusher interfaces then the returned instance also supports it.

func (*StatusCodeResponseWriter) WriteHeader

func (rw *StatusCodeResponseWriter) WriteHeader(code int)

Jump to

Keyboard shortcuts

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