goat

package module
v0.0.0-...-83ac56d Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2014 License: BSD-3-Clause Imports: 20 Imported by: 0

README

Goat Web Framework

Goat is a small web framework for Go that makes the following assumptions about your application:

  • It is using a Mongodb database and it uses mgo as a driver
  • It has a User model that has a username and password

Goat wraps the stock Go net/http library to provide a productive API for building routes for your application. Routes can have universally configured middleware that will execute on each request, or an interceptor that will only fire on specific requests.

You can find detailed documentation here: http://godoc.org/github.com/scottferg/goat

Basic usage

Add Goat to your project by importing the package

    import "github.com/scottferg/goat"

Then initialize it within your application

    g := goat.NewGoat()

You'll probably want sessions and a database in your app, so configure the middleware as well

    g.RegisterMiddleware(g.NewSessionMiddleware("mysessionstore"))
    g.RegisterMiddleware(g.NewDatabaseMiddleware("localhost", "database_name"))

Now that you're middleware is configured you can specify your routes, as well as any interceptors that you want to use

    g.RegisterRoute("/login", goat.GET|goat.POST, "login", Login)
    g.RegisterRoute("/", goat.GET, "index", goat.NewAuthSessionInterceptor(GetUserDetails, Login))
    g.RegisterStaticFileHandler("/static/")

And you're ready to start serving your app

    g.ListenAndServe("8080")

Routes

Routes can be considered controllers in the MVC sense, and adhere to the Handler type:

    func(w http.ResponseWriter, r *http.Request, c *goat.Context) error

Responses to a request can happen through the traditional methods with http.ResponseWriter. The context attached to each request is how you can access your database, session, or user from within a view handler

    type Context struct {
        Database *mgo.Database
        Session  *sessions.Session
        User     *User
    }

Note that Goat uses the Gorilla Web Toolkit under the hood for a number of functions, including session management. If you need to manipulate the session directly, you'll need to import "github.com/gorilla/sessions" or a compatible fork.

Middleware

Middleware is a higher-order function that returns a function with the following signature:

    func(r *http.Request, c *goat.Context)

Creating your own middleware is easy:

    func NewMyCoolMiddleware(awesometown string) Middleware {
        return func(r *http.Request, c *Context) error {
            // Middleware that adds a string to a users session
            c.Session.Values["coolkey"] = awesometown
            return err
        }
    }

All middleware will run in the order in which it is registered, before a handler is called on your route. Out of the box, Goat provides the following middleware:

    // Enables session management on your requests
    NewSessionMiddleware(storename string) Middleware

    // Configures a database connection and clones that connect onto each request
    NewDatabaseMiddleware(host, name string) Middleware

Interceptor

Sometimes you may want requests to perform an action that other requests shouldn't do. Since middleware isn't a viable solution in this case, Goat provides interceptors. An interceptor returns a function with a Handler type:

    func(w http.ResponseWriter, r *http.Request, c *goat.Context) error

Like middleware, interceptors are also easy to write:

    func NewMyCoolInterceptor(route Handler) Interceptor {
        // Informs the user they aren't cool if the request did not include the X-Cool-Header
        // otherwise the route will function as normal
        return func(w http.ResponseWriter, r *http.Request, c *Context) Handler {
            if h := r.Header.Get("X-Cool-Header"); h == "" {
                return func(w http.ResponseWriter, r *http.Request, c *Context) error {
                    http.Error(w, "You ain't cool!", http.StatusUnauthorized)
                    return nil
                }
            }

            return route
        }
    }

Goat provides the following interceptors for you:

    // Authenticates a request via basic auth
    NewBasicAuthInterceptor(normal Handler) Interceptor

    // Verifies that the session associated with this request has a goat.User associated with it,
    // otherwise it redirects to unauthorized
    NewAuthSessionInterceptor(normal, unauthorized Handler) Interceptor

Templates

Goat provides some conveniences for the built-in html/template package, provided that you parse your templates through the framework:

tFuncs = map[string]interface{}{
	"truncate":   truncate,
	"prettyDate": prettyDate,
}
ts = goat.ParseTemplates("templates", "templates/*.html", tFuncs, []string{"{%", "%}"})

Convenience template functions can be found in the package documentation.

Documentation

Index

Constants

View Source
const (
	GET    = 1 << 0
	POST   = 1 << 1
	PUT    = 1 << 2
	DELETE = 1 << 3
)

Variables

This section is empty.

Functions

func Generic401

func Generic401(w http.ResponseWriter, r *http.Request, c *Context) error

func Generic403

func Generic403(w http.ResponseWriter, r *http.Request, c *Context) error

func ObjectIdHex

func ObjectIdHex(id bson.ObjectId) string

func ParseTemplates

func ParseTemplates(name, path string, funcs template.FuncMap, delims []string) *template.Template

func ResetPassword

func ResetPassword(token, password string, c *Context) error

Types

type Config

type Config struct {
	Spdy bool
}

type Context

type Context struct {
	Database *mgo.Database
	Session  *sessions.Session
	User     *User
}

func NewContext

func NewContext() (*Context, error)

func (*Context) ClearSession

func (c *Context) ClearSession(w http.ResponseWriter, r *http.Request)

func (*Context) Close

func (c *Context) Close()

type Goat

type Goat struct {
	Router *mux.Router
	Config Config
	// contains filtered or unexported fields
}

func New

func New(c *Config) *Goat

func (*Goat) CloneDB

func (g *Goat) CloneDB() *mgo.Database

func (*Goat) Close

func (g *Goat) Close()

func (*Goat) CopyDB

func (g *Goat) CopyDB() *mgo.Database

func (*Goat) ListenAndServe

func (g *Goat) ListenAndServe(port string) error

func (*Goat) ListenAndServeTLS

func (g *Goat) ListenAndServeTLS(cert, key, addr string) error

func (*Goat) NewDatabaseMiddleware

func (g *Goat) NewDatabaseMiddleware(host, name string) Middleware

func (*Goat) NewSessionMiddleware

func (g *Goat) NewSessionMiddleware(storename string) Middleware

func (*Goat) RegisterMiddleware

func (g *Goat) RegisterMiddleware(m Middleware)

func (*Goat) RegisterRoute

func (g *Goat) RegisterRoute(path, name string, method int, handler interface{})

func (*Goat) RegisterStaticFileHandler

func (g *Goat) RegisterStaticFileHandler(remote, local string)

func (*Goat) Reverse

func (g *Goat) Reverse(root string, params ...string) (*url.URL, error)

type Handler

type Handler func(http.ResponseWriter, *http.Request, *Context) error

type Interceptor

type Interceptor func(http.ResponseWriter, *http.Request, *Context) Handler

func NewAuthSessionInterceptor

func NewAuthSessionInterceptor(normal, unauthorized Handler) Interceptor

func NewBasicAuthInterceptor

func NewBasicAuthInterceptor(normal Handler) Interceptor

type Middleware

type Middleware func(*http.Request, *Context) error

type ResetToken

type ResetToken struct {
	Id        bson.ObjectId
	Username  string
	Token     string
	Timestamp time.Time
}

func RequestResetToken

func RequestResetToken(username string, c *Context) (*ResetToken, error)

Fetches a request token for the user. If the user is found, they will be added to the provided context.

func (*ResetToken) Delete

func (r *ResetToken) Delete(c *Context) error

func (*ResetToken) Save

func (r *ResetToken) Save(c *Context) error

type User

type User struct {
	Id       bson.ObjectId          `json:"-" bson:"_id,omitempty"`
	Username string                 `json:"username,omitempty" bson:"username,omitempty"`
	Password []byte                 `json:"-" bson:"password,omitempty"`
	Values   map[string]interface{} `json:"values,omitempty" bson:"values,omitempty"`
}

func Authenticate

func Authenticate(username, password string, c *Context) (u *User, err error)

Login validates and returns a user object if they exist in the database.

func FindUser

func FindUser(username string, c *Context) (u *User, err error)

func NewUser

func NewUser(username, password string, c *Context) (u *User, err error)

func (*User) Login

func (u *User) Login(w http.ResponseWriter, r *http.Request, c *Context)

func (*User) Save

func (u *User) Save(c *Context) (err error)

func (*User) SetPassword

func (u *User) SetPassword(password string) error

SetPassword takes a plaintext password and hashes it with bcrypt and sets the password field to the hash.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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