beacon

package
v0.1.1-0...-f25bbfc Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2013 License: Apache-2.0 Imports: 14 Imported by: 0

README

RESTFul framework

Yet an other RESTful interface between http requests and jobs. But it comes with its modular and simple way to do that and ease the building of such a popular and efficient web interface.

The goal is to provide a powerful framework that let you focus on your API design and the available methods your users can reach, without worrying about so-standard process between.

The project makes heavy use of etcd as a highly-available centralized configuration storage. Server and clients preferences are easily stored and accessed from a (soon...) ssl-secured etcd cluster database. Please notice it is implemented behind a Controller abstraction that will allow to easily integrate other storage systems in the futur.

Batteries inluded

  • Dead easy to use, build serious applications in minutes
  • Http standard authentification
  • Permission per user per Method
  • Plug and play endpoints, authentification and permission methods
  • But not only, up to 2 filters actually before endpoint processing
  • Secured, higly-available and centralized configuration storage
  • Mysql-ready for users logins
  • Debug client provided, easy to write one
  • Ready for load-balancing and multi-hosts
  • Built-in profiling
  • 21st century tests

Suit up

First make sure etcd binary is available in your $PATH.

go get -v github.com/hivetech/hivy/beacon

Or For development (it will setup etcd)

$ git clone https://github.com/hivetech/hivy.git
$ rake install
$ rake tests:check

Usage

Let's add a new service to our app:

  • Implement a method with this signature: func YourMethod(request *restful.Request, response *restful.Response)
  • Create an authority with authentification and permission methods: a := NewAuthority(authMethod, permissionMethod)
  • Finally, map the service: a.Map("METHOD /path/with/{parameter}", endpoint.YourMethod)

It is possible to register at a same path multiple endpoints to multiple http methods. Check out app/hivy.go to take a glance at it. We can see as well where to insert custom authentification, permission or any filter method. Those must have the following signature:

func YourFilter(request *restful.Request, response *restful.Response, chain *restful.FilterChain) {
    // Filter whatever you want here
    chain.ProcessFilter(request, response)
}

Code Example

func authenticate(request *restful.Request, response *restful.Response, chain *restful.FilterChain) {
    user, pass, _ := security.Credentials(request)
    if user != "Chuck" || pass != "Norris" {  
        err := fmt.Errorf("you are not chuck norris")
        endpoints.HTTPAuthroizationError(response, err)
        return 
    }
    chain.ProcessFilter(request, response)
}

func control(request *restful.Request, response *restful.Response, chain *restful.FilterChain) {
    method := fmt.Sprintf("%s%s", request.Request.Method, request.Request.URL)
    if strings.Contains(method, "deploy") {
        err := fmt.Errorf("deploy method is not supported")
        endpoints.HTTPBadRequestError(response, err)
        return
    }
    chain.ProcessFilter(request, response)
}

func main() {
    router := NewRouter(authenticate, control, profile)

    router.Map("GET juju/{command}", endpoints.Juju)
    router.Map("GET help/", endpoints.Help)

    var userMap = map[string]restful.RouteFunction{
        "PUT user/": endpoints.CreateUser,
        "DELETE user/": endpoints.DeleteUser,
    }
    router.MultiMap(userMap)

    log.Infof("Hivy interface serving on %s\n", url)
    http.ListenAndServe("127.0.0.1:8080", nil)
}

Documentation

Index

Constants

View Source
const (

	// Allowed is a macro representing an accessible method
	Allowed string = "true"
	// Forbidden is a macro representing an hiden method
	Forbidden string = "false"
)
View Source
const (
	// MaxMachinesRule restritcs number of deployments allowed
	// Note that multi-machines deployment counts for one
	MaxMachinesRule int = 10
)

Variables

This section is empty.

Functions

func BasicAuthenticate

func BasicAuthenticate(req *restful.Request, resp *restful.Response, chain *restful.FilterChain)

BasicAuthenticate is an intermediate step that will check encoded credentials before processing the received request. This function is explicitely used in Register() as a filter in the request pipeline.

func CatchInterruption

func CatchInterruption(stop chan bool)

CatchInterruption handles SIGINT signal to clean the application before exiting. If th stop channel exists it will trigger a signal usuable elsewhere

func EtcdControlMethod

func EtcdControlMethod(request *restful.Request, response *restful.Response, chain *restful.FilterChain)

EtcdControlMethod is a callback part of the request pipeline. It checks in etcd if the received request is allowed for the given user.

func FormatMethod

func FormatMethod(request *restful.Request) string

FormatMethod extracts and concatenate from http request the method and the url, minus the pararmeters. Mostly used further to control the method in the database

func HTTPAuthorizationError

func HTTPAuthorizationError(writer *restful.Response, err error)

HTTPAuthorizationError handles permission failure

func HTTPBadRequestError

func HTTPBadRequestError(writer *restful.Response, err error)

HTTPBadRequestError handles unknown requests

func HTTPInternalError

func HTTPInternalError(writer *restful.Response, err error)

HTTPInternalError handles server errors

func IdentityFilter

func IdentityFilter(request *restful.Request, response *restful.Response, chain *restful.FilterChain)

IdentityFilter does nothing but continuing

func RunEtcd

func RunEtcd(stop chan bool, name, directory, clientIP, raftIP, clusterIP string,
	force, verbose bool, profile bool)

RunEtcd launchs an http-based key-value storage that holds user and system configuration. Here is spawned a new instance, restricted to relevant command line flags for hivy application.

func SetupLog

func SetupLog(appModules []string, verbose bool, logfile string) error

SetupLog set application's modules log level

Types

type Controller

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

Controller knows about rules, constraints and has methods to check them

func NewController

func NewController(user string, debug bool) *Controller

NewController setup debug mode and return an initialized controller

func (*Controller) CheckMethod

func (c *Controller) CheckMethod(method string) (bool, error)

CheckMethod makes sure the given one is like GET/path/to/endpoint (without parameters)

func (*Controller) Delete

func (c *Controller) Delete(path string) (*etcd.Response, error)

Delete wraps go-etcd Delete method

func (*Controller) DisableMethod

func (c *Controller) DisableMethod(method string) error

DisableMethod makes the given method forbidden for the currently controlled user (i.e. c.user)

func (*Controller) EnableMethod

func (c *Controller) EnableMethod(method string) error

EnableMethod makes the given method available for the currently controlled user (i.e. c.user)

func (*Controller) Get

func (c *Controller) Get(path string) ([]*etcd.Response, error)

Get wraps go-etcd Get method

func (*Controller) Ressource

func (c *Controller) Ressource(name string) (string, error)

Ressource the current state or value of the given ressource name Localtion: v1/keys/hivy/security/{user}/ressources/{ressource}

func (*Controller) Set

func (c *Controller) Set(key, value string, ttl uint64) (*etcd.Response, error)

Set wraps go-etcd Set method

func (*Controller) SetUser

func (c *Controller) SetUser(user string)

SetUser changes the user currently controlled

func (*Controller) Update

func (c *Controller) Update(method string) error

Update actualize states in the database regarding the given request

type Router

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

Router is the main functionnal entry point

func NewRouter

func NewRouter(a, c restful.FilterFunction, profiling bool) *Router

NewRouter needs one function handling user/pass authetification, and one function handling method permission for the user who requested it.

func (*Router) Map

func (a *Router) Map(request string, callback restful.RouteFunction) error

Map lets you design your API. When registered to hivy, user-defined callback function are processed when "path" is reached by authentified requests Example:

router.Map("GET hello/{world}", func(req, resp) {fmt.Println("Hello world")})

func (*Router) MultiMap

func (a *Router) MultiMap(mapping map[string]restful.RouteFunction) error

MultiMap allows app to associate different endpoints under the same root path with different http methods

type Version

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

Version follows unstable git tag

func StableVersion

func StableVersion() Version

StableVersion is a Modest accessor TODO Read git tag to make it automatic

func (*Version) String

func (v *Version) String() string

Jump to

Keyboard shortcuts

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