weavebox

package module
v0.9.7 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2015 License: MIT Imports: 19 Imported by: 10

README

weavebox GoDoc Travis CI

Minimalistic web framework for the Go programming language.

Installation

go get github.com/twanies/weavebox

Features

  • fast route dispatching backed by httprouter
  • easy to add middleware handlers
  • subrouting with seperated middleware handlers
  • central based error handling
  • build in template engine
  • fast, lightweight and extendable

Basic usage

package main
import "github.com/twanies/weavebox"

func main() {
    app := weavebox.New()

    app.Get("/foo", fooHandler)
    app.Post("/bar", barHandler)
    app.Use(middleware1, middleware2)

    friends := app.Box("/friends")
    friends.Get("/profile", profileHandler)
    friends.Use(middleware3, middleware4)
    
    app.Serve(8080)
}

More complete examples can be found in the examples folder

Routes

app := weavebox.New()

app.Get("/", func(ctx *weavebox.Context) error {
   .. do something .. 
})
app.Post("/", func(ctx *weavebox.Context) error {
   .. do something .. 
})
app.Put("/", func(ctx *weavebox.Context) error {
   .. do something .. 
})
app.Delete("/", func(ctx *weavebox.Context) error {
   .. do something .. 
})

get named url parameters

app.Get("/hello/:name", func(ctx *weavebox.Context) error {
    name := ctx.Param("name")
})

Box (subrouting)

Box lets you manage routes, contexts and middleware separate from each other.

Create a new weavebox object and attach some middleware and context to it.

app := weavebox.New()
app.BindContext(context.WithValue(context.Background(), "foo", "bar")
app.Get("/", somHandler)
app.Use(middleware1, middleware2)

Create a box and attach its own middleware and context to it

friends := app.Box("/friends")
app.BindContext(context.WithValue(context.Background(), "friend1", "john")
friends.Post("/create", someHandler)
friends.Use(middleware3, middleware4)

In this case box friends will inherit middleware1 and middleware2 from its parent app. We can reset the middleware from its parent by calling Reset()

friends := app.Box("/friends").Reset()
friends.Use(middleware3, middleware4)

Now box friends will have only middleware3 and middleware4 attached.

Static files

Make our assets accessable trough /assets/styles.css

app := weavebox.New()
app.Static("/assets", "public/assets")

Handlers

A definition of a weavebox.Handler
func(ctx *weavebox.Context) error

Weavebox only accepts handlers of type weavebox.Handler to be passed as functions in routes. You can convert any type of handler to a weavebox.Handler with the decorater pattern.

func myHandler(name string) weavebox.Handler{
    .. do something ..
   return func(ctx *weavebox.Context) error {
        return ctx.Text(http.StatusOK, name)
   }
}
Returning errors

Each handler requires an error to be returned. This is personal idiom but it brings some benifits for handling your errors inside request handlers.

func someHandler(ctx *weavebox.Context) error {
    // simple error handling by returning all errors 
    err := someFunc(); err != nil {
        return err
    }
    ...
    req, err := http.NewRequest(...)
    if err != nil {
        return err
    }
}

A weavebox ErrorHandlerFunc

func(ctx *weavebox.Context, err error)

Handle all errors returned by adding a custom errorHandler for our application.

app := weavebox.New()
errHandler := func(ctx *weavebox.Context, err error) {
    .. handle the error ..
}
app.SetErrorHandler(errHandler)

Context

Context is a request based object helping you with a series of functions performed against the current request scope.

Passing values arround middleware functions

Context provides a context.Context for passing request scoped values arround middleware functions.

Create a new context and pass some values

func someMiddleware(ctx *weavebox.Context) error {
    ctx.Context = context.WithValue(ctx.Context, "foo", "bar")
    return someMiddleware2(ctx)
}

Get the value back from the context in another middleware function

func someMiddleware2(ctx *weavebox.Context) error {
    value := ctx.Context.Value("foo").(string)
    ..
}
Binding a context

In some cases you want to intitialize a context from the the main function, like a datastore for example. You can set a context out of a request scope by calling BindContext().

app.BindContext(context.WithValue(context.Background(), "foo", "bar"))

As mentioned in the Box section, you can add different contexts to different boxes.

mybox := app.Box("/foo", ..)
mybox.BindContext(..)
Helper functions

Context also provides a series of helper functions like responding JSON en text, JSON decoding etc..

func createUser(ctx *weavebox.Context) error {
    user := model.User{}
    if err := ctx.DecodeJSON(&user); err != nil {
        return errors.New("failed to decode the response body")
    }
    ..
    return ctx.JSON(http.StatusCreated, user)
}

func login(ctx *weavebox.Context) error {
    token := ctx.Header("x-hmac-token")
    if token == "" {
        ctx.Redirect("/login", http.StatusMovedPermanently)
        return nil
    }
    ..
}

View / Templates

Logging

Access Log

Weavebox provides an access-log in an Apache log format for each incomming request. The access-log is disabled by default, to enable the access-log set app.EnableAccessLog = true.

127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326

Logging errors and information

Server

Weavebox HTTP server is a wrapper arround the default std HTTP server, the only difference is that it provides a gracefull shutdown. Weavebox provides both HTTP and HTTPS (TLS).

app := weavebox.New()
app.ServeTLS(8080, cert, key)
// or 
app.Serve(8080)
Gracefull stopping a weavebox app

Gracefull stopping a weavebox app is done by sending one of these signals to the process.

  • SIGINT
  • SIGQUIT
  • SIGTERM

You can also force-quit your app by sending it SIGKILL signal

SIGUSR2 signal is not yet implemented. Reloading a new binary by forking the main process is something that wil be implemented when the need for it is there. Feel free to give some feedback on this feature if you think it can provide a bonus to the package.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Box

type Box struct {
	Weavebox
}

Box act as a subrouter and wil inherit all of its parents middleware

func (*Box) Reset

func (b *Box) Reset() *Box

Reset clears all middleware

type Context

type Context struct {
	// Context is a idiomatic way to pass information between requests.
	// More information about context.Context can be found here:
	// https://godoc.org/golang.org/x/net/context
	Context context.Context
	// contains filtered or unexported fields
}

Context is required in each weavebox Handler and can be used to pass information between requests.

func (*Context) DecodeJSON

func (c *Context) DecodeJSON(v interface{}) error

DecodeJSON is a helper that decodes the request Body to v. For a more in depth use of decoding and encoding JSON, use the std JSON package.

func (*Context) Form

func (c *Context) Form(name string) string

Form returns the form parameter by its name

func (*Context) Header

func (c *Context) Header(name string) string

Header returns the request header by name

func (*Context) JSON

func (c *Context) JSON(code int, v interface{}) error

JSON is a helper function for writing a JSON encoded representation of v to the ResponseWriter.

func (*Context) Param

func (c *Context) Param(name string) string

Param returns the url named parameter given in the route prefix by its name

app.Get("/:name", ..) => ctx.Param("name")

func (*Context) Query

func (c *Context) Query(name string) string

Query returns the url query parameter by its name.

app.Get("/api?limit=25", ..) => ctx.Query("limit")

func (*Context) Redirect

func (c *Context) Redirect(url string, code int) error

Redirect redirects the request to the provided URL with the given status code.

func (*Context) Render

func (c *Context) Render(name string, data interface{}) error

Render calls the templateEngines Render function

func (*Context) Request

func (c *Context) Request() *http.Request

Request returns a default http.Request ptr

func (*Context) Response

func (c *Context) Response() http.ResponseWriter

Response returns a default http.ResponseWriter

func (*Context) SetHeader added in v0.9.6

func (c *Context) SetHeader(key, value string)

SetHeader set a header to the response. If the header allready exists the value will be overidden.

func (*Context) Text

func (c *Context) Text(code int, text string) error

Text is a helper function for writing a text/plain string to the ResponseWriter

type ErrorHandlerFunc

type ErrorHandlerFunc func(ctx *Context, err error)

ErrorHandlerFunc is invoked when a Handler returns an error, and can be used to centralize error handling.

type Handler

type Handler func(ctx *Context) error

Handler is a weavebox idiom for handling http.Requests

type Renderer

type Renderer interface {
	Render(w io.Writer, name string, data interface{}) error
}

Renderer renders any kind of template. Weavebox allows the use of different template engines, if they implement the Render method.

type TemplateEngine

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

TemplateEngine provides simple, fast and powerfull rendering of HTML pages.

func NewTemplateEngine

func NewTemplateEngine(root string) *TemplateEngine

NewTemplateEngine returns a new TemplateEngine object that will look for templates at the given root.

func (*TemplateEngine) Init

func (t *TemplateEngine) Init()

Init parses all the given singel and layout templates. And stores them in the template cache.

func (*TemplateEngine) Render

func (t *TemplateEngine) Render(w io.Writer, name string, data interface{}) error

Render renders the template and satisfies the weavebox.Renderer interface.

func (*TemplateEngine) SetTemplates

func (t *TemplateEngine) SetTemplates(templates ...string)

SetTemplates sets single templates that not need to be parsed with a layout

func (*TemplateEngine) SetTemplatesWithLayout

func (t *TemplateEngine) SetTemplatesWithLayout(layout string, templates ...string)

SetTemplatesWithLayout sets a layout and parses all given templates with that layout.

type Weavebox

type Weavebox struct {
	// ErrorHandler is invoked whenever a Handler returns an error
	ErrorHandler ErrorHandlerFunc

	// Output writes the access-log and debug parameters
	Output io.Writer

	// EnableAccessLog lets you turn of the default access-log
	EnableAccessLog bool

	// HTTP2 enables the HTTP2 protocol on the server. HTTP2 wil be default proto
	// in the future. Currently browsers only supports HTTP/2 over encrypted TLS.
	HTTP2 bool
	// contains filtered or unexported fields
}

Weavebox first class object that is created by calling New()

func New

func New() *Weavebox

New returns a new Weavebox object

func (*Weavebox) BindContext

func (w *Weavebox) BindContext(ctx context.Context)

BindContext lets you provide a context that will live a full http roundtrip BindContext is mostly used in a func main() to provide init variables that may be created only once, like a database connection. If BindContext is not called, weavebox will use a context.Background()

func (*Weavebox) Box

func (w *Weavebox) Box(prefix string) *Box

Box returns a new Box that will inherit all of its parents middleware. you can reset the middleware registered to the box by calling Reset()

func (*Weavebox) Delete

func (w *Weavebox) Delete(route string, h Handler)

Delete registers a route prefix and will invoke the Handler when the route matches the prefix and the request METHOD is DELETE

func (*Weavebox) Get

func (w *Weavebox) Get(route string, h Handler)

Get registers a route prefix and will invoke the Handler when the route matches the prefix and the request METHOD is GET

func (*Weavebox) Handle added in v0.9.4

func (w *Weavebox) Handle(method, path string, h http.Handler)

Handle adapts the usage of an http.Handler and will be invoked when the router matches the prefix and request method

func (*Weavebox) Head added in v0.9.5

func (w *Weavebox) Head(route string, h Handler)

Head registers a route prefix and will invoke the Handler when the route matches the prefix and the request METHOD is HEAD

func (*Weavebox) Options added in v0.9.5

func (w *Weavebox) Options(route string, h Handler)

Options registers a route prefix and will invoke the Handler when the route matches the prefix and the request METHOD is OPTIONS

func (*Weavebox) Post

func (w *Weavebox) Post(route string, h Handler)

Post registers a route prefix and will invoke the Handler when the route matches the prefix and the request METHOD is POST

func (*Weavebox) Put

func (w *Weavebox) Put(route string, h Handler)

Put registers a route prefix and will invoke the Handler when the route matches the prefix and the request METHOD is PUT

func (*Weavebox) Serve

func (w *Weavebox) Serve(port int) error

Serve serves the application on the given port

func (*Weavebox) ServeCustom added in v0.9.2

func (w *Weavebox) ServeCustom(s *http.Server) error

ServeCustom serves the application with custom server configuration.

func (*Weavebox) ServeCustomTLS added in v0.9.2

func (w *Weavebox) ServeCustomTLS(s *http.Server, certFile, keyFile string) error

ServeCustomTLS serves the application with TLS encription and custom server configuration.

func (*Weavebox) ServeHTTP

func (w *Weavebox) ServeHTTP(rw http.ResponseWriter, r *http.Request)

ServeHTTP satisfies the http.Handler interface

func (*Weavebox) ServeTLS

func (w *Weavebox) ServeTLS(port int, certFile, keyFile string) error

ServeTLS serves the application one the given port with TLS encription.

func (*Weavebox) SetErrorHandler added in v0.9.3

func (w *Weavebox) SetErrorHandler(h ErrorHandlerFunc)

SetErrorHandler sets a centralized errorHandler that is invoked whenever a Handler returns an error.

func (*Weavebox) SetMethodNotAllowed added in v0.9.3

func (w *Weavebox) SetMethodNotAllowed(h http.Handler)

SetMethodNotAllowed sets a custom handler that is invoked whenever the router could not match the method against the predefined routes.

func (*Weavebox) SetNotFoundHandler added in v0.9.2

func (w *Weavebox) SetNotFoundHandler(h http.Handler)

SetNotFoundHandler sets a custom handler that is invoked whenever the router could not match a route against the request url.

func (*Weavebox) SetTemplateEngine

func (w *Weavebox) SetTemplateEngine(t Renderer)

SetTemplateEngine allows the use of any template engine out there, if it satisfies the Renderer interface

func (*Weavebox) Static

func (w *Weavebox) Static(prefix, dir string)

Static registers the prefix to the router and start to act as a fileserver

app.Static("/public", "./assets")

func (*Weavebox) Use

func (w *Weavebox) Use(handlers ...Handler)

Use appends a Handler to the box middleware. Different middleware can be set for each subrouter (Box).

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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