scroll

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Dec 22, 2014 License: Apache-2.0, Apache-2.0 Imports: 14 Imported by: 0

README

WORK IN PROGRESS

scroll

Scroll is a lightweight library for building Go HTTP services at Mailgun.

Example

package main

import (
    "fmt"
    "net/http"

    "github.com/mailgun/scroll"
)

func handler(w http.ResponseWriter, r *http.Request, params map[string]string) (interface{}, error) {
    return scroll.Response{
        "message": fmt.Sprintf("Resource ID: %v", params["resourceID"]),
    }, nil
}

func main() {
    // create an app
    appConfig := scroll.AppConfig{
        Name:     "scrollexample",
        Host:     "0.0.0.0",
        Port:     8080,
        Register: false,
    }
    app := scroll.NewApp(&appConfig)

    // register a handler
    handlerConfig := scroll.HandlerConfig{
        Methods:  []string{"GET", "POST"},
        Path:     "/resources/{resourceID}",
        Register: false,
    }
    app.AddHandler(handler, &handlerConfig)

    // start the app
    app.Run()
}

Documentation

Index

Constants

View Source
const (
	// Suggested result set limit for APIs that may return many entries (e.g. paging).
	DefaultLimit int = 100

	// Suggested max allowed result set limit for APIs that may return many entries (e.g. paging).
	MaxLimit int = 10000

	// Suggested max allowed amount of entries that batch APIs can accept (e.g. batch uploads).
	MaxBatchSize int = 1000
)

Variables

This section is empty.

Functions

func GetIntField

func GetIntField(r *http.Request, fieldName string) (int, error)

Retrieve a POST request field as an integer. Returns `MissingFieldError` if requested field is missing.

func GetMultipleFields

func GetMultipleFields(r *http.Request, fieldName string) ([]string, error)

Retrieve fields with the same name as an array of strings.

func GetStringField

func GetStringField(r *http.Request, fieldName string) (string, error)

Retrieve a POST request field as a string. Returns `MissingFieldError` if requested field is missing.

func GetStringFieldWithDefault

func GetStringFieldWithDefault(r *http.Request, fieldName, defaultValue string) string

Retrieve a POST request field as a string. If the requested field is missing, returns provided default value.

func GetTimestampField

func GetTimestampField(r *http.Request, fieldName string) (time.Time, error)

Helper method to retrieve an optional timestamp from POST request field. If no timestamp provided, returns current time. Returns `InvalidFormatError` if provided timestamp can't be parsed.

func MakeHandler

func MakeHandler(app *App, fn HandlerFunc, spec Spec) http.HandlerFunc

Wraps the provided handler function encapsulating boilerplate code so handlers do not have to implement it themselves: parsing a request's form, formatting a proper JSON response, emitting the request stats, etc.

func MakeHandlerWithBody

func MakeHandlerWithBody(app *App, fn HandlerWithBodyFunc, spec Spec) http.HandlerFunc

Make a handler out of HandlerWithBodyFunc, just like regular MakeHandler function.

func Reply

func Reply(w http.ResponseWriter, response interface{}, status int)

Reply with the provided HTTP response and status code.

Response body must be JSON-marshallable, otherwise the response will be "Internal Server Error".

func ReplyError

func ReplyError(w http.ResponseWriter, err error)

ReplyError converts registered error into HTTP response code and writes it back.

func ReplyInternalError

func ReplyInternalError(w http.ResponseWriter, message string)

Helper that replies with the 500 code and happened error message.

Types

type App

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

Represents an app.

func NewApp

func NewApp() *App

Create a new app.

func NewAppWithConfig

func NewAppWithConfig(config AppConfig) *App

Create a new app with the provided configuration.

func (*App) AddHandler

func (app *App) AddHandler(spec Spec) error

Register a handler function.

If vulcand registration is enabled in the both app config and handler spec, the handler will be registered in the local etcd instance.

func (*App) GetHandler

func (app *App) GetHandler() http.Handler

GetHandler returns HTTP compatible Handler interface.

func (*App) Run

func (app *App) Run() error

Start the app on the configured host/port.

If vulcand registration is enabled in the app config, starts a goroutine that will be registering the app's endpoint once every minute in the local etcd instance.

Supports graceful shutdown on 'kill' and 'int' signals.

func (*App) SetNotFoundHandler

func (app *App) SetNotFoundHandler(fn http.HandlerFunc)

SetNotFoundHandler sets the handler for the case when URL can not be matched by the router.

type AppConfig

type AppConfig struct {
	// name of the app being created
	Name string

	// host the app is intended to bind to
	Host string

	// port the app is going to listen on
	Port int

	// optional router to use
	Router *mux.Router

	// hostname of the public API entrypoint used for vulcand registration
	APIHost string

	// whether to register the app's endpoint and handlers in vulcand
	Register bool

	// metrics service used for emitting the app's real-time metrics
	Client metrics.Client
}

Represents a configuration object an app is created with.

type ConflictError

type ConflictError struct {
	Description string
}

func (ConflictError) Error

func (e ConflictError) Error() string

type GenericAPIError

type GenericAPIError struct {
	Reason string
}

func (GenericAPIError) Error

func (e GenericAPIError) Error() string

type HandlerFunc

type HandlerFunc func(http.ResponseWriter, *http.Request, map[string]string) (interface{}, error)

Defines the signature of a handler function that can be registered by an app.

The 3rd parameter is a map of variables extracted from the request path, e.g. if a request path was:

/resources/{resourceID}

and the request was made to:

/resources/1

then the map will contain the resource ID value:

{"resourceID": 1}

A handler function should return a JSON marshallable object, e.g. Response.

type HandlerWithBodyFunc

type HandlerWithBodyFunc func(http.ResponseWriter, *http.Request, map[string]string, []byte) (interface{}, error)

Defines a signature of a handler function, just like HandlerFunc.

In addition to the HandlerFunc a request's body is passed into this function as a 4th parameter.

type InvalidFormatError

type InvalidFormatError struct {
	Field string
	Value string
}

func (InvalidFormatError) Error

func (e InvalidFormatError) Error() string

type InvalidParameterError

type InvalidParameterError struct {
	Field string
	Value string
}

func (InvalidParameterError) Error

func (e InvalidParameterError) Error() string

type MissingFieldError

type MissingFieldError struct {
	Field string
}

func (MissingFieldError) Error

func (e MissingFieldError) Error() string

type NotFoundError

type NotFoundError struct {
	Description string
}

func (NotFoundError) Error

func (e NotFoundError) Error() string

type Response

type Response map[string]interface{}

Response objects that apps' handlers are advised to return.

Allows to easily return JSON-marshallable responses, e.g.:

Response{"message": "OK"}

type Spec

type Spec struct {
	// List of HTTP methods the handler should match.
	Methods []string

	// Path the handler should match.
	Path string

	// Key/value pairs of specific HTTP headers the handler should match (e.g. Content-Type).
	Headers []string

	// A handler function to use. Just one of these should be provided.
	RawHandler      http.HandlerFunc
	Handler         HandlerFunc
	HandlerWithBody HandlerWithBodyFunc

	// Unique identifier used when emitting performance metrics for the handler.
	MetricName string

	// Whether to register the handler in vulcand.
	Register bool
}

Represents handler's specification.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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