webapp

package module
v0.0.0-...-370a347 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2015 License: MIT Imports: 15 Imported by: 0

README

webapp

helper functions for web application

current status: WIP

webapp uses a modified gorilla/mux router found in zdebeer99/mux and negroni for managing middleware.

Overview

API Documentation https://gowalker.org/github.com/zdebeer99/webapp

Features

To provide a simple one stop library that has the following built-in:

  • Session Management
  • Easy Access to database
  • Basic User Authentication
  • Rendering
  • Html form and json parsing to schemas.

How it should work

  • Use a context structure per request instead of the default http.handlers The reason for this is personal preference, and the draw back is that you must change the context struct to tailor it to your needs, the advantage is that you can pass data between middleware layers without a external context, and keep casting to a minimum.
  • Middleware [Done] - Using Negroni Embeded
  • Routing [Done] - Using gorilla mux
  • Session Management
  • MongoDB Support
  • Data Bindings like form, json, etc

Basic Web app

Routing

Middleware

the following middleware is included in webapp.

  • Recovery - Copied from negroni
  • Logger - Copied from negroni
  • MongoDB - Activate a mongodb connection

Custom Middleware

Middleware can be added from the Use(...) and UseFunc(...) functions. Custom Middleware requires a 'c *Context, next HandlerFunc' signature.

Example of middleware requiring user login before opening the page:

  r:=webapp.New()
  r.UseFunc(func(c *webapp.Context, next webapp.Handler) {
    if c.Auhtenticate(){
      next(c)
    }else{
      c.Redirect("/login")
    }
  })

Rendering

Context API Reference

Vars map containing route variables.

app.Get("getItem/{id}",getItem)

func getItem(c *webapp.Context){
  id := c.Vars["id"].(string)
  .
  .
  .
}

Documentation

Overview

Web App Helper functions.

Index

Constants

View Source
const (
	KeySessionId      = "SessionId"
	KeyDatabaseObject = "DatabaseObject"
	KeyUser           = "User"
)

Variables

This section is empty.

Functions

func Form2M

func Form2M(values url.Values) map[string]interface{}

func ValidateInt

func ValidateInt(value, min, max int) error

func ValidateString

func ValidateString(value string, minlength, maxlength int) error

func WebappHandlerFunc

func WebappHandlerFunc(f func(*Context)) func(interface{})

WebappHandler Wrap a mux handler and calls a webapp handler

func WriteJson

func WriteJson(w http.ResponseWriter, model interface{}) error

func WriteString

func WriteString(w http.ResponseWriter, format string, data ...interface{})

Types

type Context

type Context struct {
	*mux.HandlerContext

	Session   Session
	SessionId string
	User      UserManager
	// contains filtered or unexported fields
}

func NewContext

func NewContext(app *Webapp, w http.ResponseWriter, req *http.Request) *Context

func (*Context) App

func (this *Context) App() *Webapp

func (*Context) Auhtenticate

func (this *Context) Auhtenticate() bool

func (*Context) BindForm

func (this *Context) BindForm(model interface{})

BindForms binds a go structure to a html form Uses gorilla.schema

func (*Context) BindJson

func (this *Context) BindJson(model interface{})

func (*Context) DB

func (this *Context) DB() *mgo.Database

DB get a mgo.Database instance for a mongo database. This function can be modified to return your database instance. The MongoDB Middleware must be used for this function to work.

func (*Context) Error

func (this *Context) Error(errormessage string, code int)

func (*Context) File

func (this *Context) File(filePath string)

File return a file from a path

func (*Context) Form

func (this *Context) Form() url.Values

func (*Context) Get

func (this *Context) Get(name string) interface{}

Get a value that was set on this request context.

func (*Context) GetAll

func (this *Context) GetAll() map[string]interface{}

Get all values that was set on this request context.

func (*Context) Http

func (this *Context) Http() (ResponseWriter, *http.Request)

func (*Context) Json

func (this *Context) Json(model interface{})

View Render a template to html. By default gojade rendering engine is used, this can be customized.

func (*Context) PostForm

func (this *Context) PostForm() url.Values

func (*Context) Redirect

func (this *Context) Redirect(path string)

func (*Context) ResponseWriter

func (this *Context) ResponseWriter() ResponseWriter

func (*Context) Set

func (this *Context) Set(name string, value interface{})

Set a value on this request context.

func (*Context) View

func (this *Context) View(view string, model interface{})

View Render a template to html. By default gojade rendering engine is used, this can be customized.

func (*Context) ViewString

func (this *Context) ViewString(format string, data ...interface{})

Return a String to the client.

type Handler

type Handler interface {
	ServeHTTP(c *Context)
}

type HandlerFunc

type HandlerFunc func(c *Context)

func (HandlerFunc) ServeHTTP

func (h HandlerFunc) ServeHTTP(c *Context)

type Html

type Html struct {
	ViewModel *ViewModel
	Context   *Context
}

Html is bounded in the ViewModel to allow helper functions to be called from the view.

func (*Html) Human

func (this *Html) Human(value interface{}) string

Human() display's a basic type to a more human readible format.

type JadeRenderer

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

func NewJadeRender

func NewJadeRender(viewpath string) *JadeRenderer

func (*JadeRenderer) Render

func (this *JadeRenderer) Render(c *Context, view string, model interface{})

type Logger

type Logger struct {
	// Logger inherits from log.Logger used to log messages with the Logger middleware
	*log.Logger
}

Logger is a middleware handler that logs the request as it goes in and the response as it goes out.

func NewLogger

func NewLogger() *Logger

NewLogger returns a new Logger instance

func (*Logger) ServeHTTP

func (l *Logger) ServeHTTP(c *Context, next HandlerFunc)

type MiddlewareHandler

type MiddlewareHandler interface {
	//ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)
	ServeHTTP(c *Context, next HandlerFunc)
}

Handler handler is an interface that objects can implement to be registered to serve as middleware in the Negroni middleware stack. ServeHTTP should yield to the next middleware in the chain by invoking the next http.HandlerFunc passed in.

If the Handler writes to the ResponseWriter, the next http.HandlerFunc should not be invoked.

func Wrap

func Wrap(handler Handler) MiddlewareHandler

Wrap converts a http.Handler into a negroni.Handler so it can be used as a Negroni middleware. The next http.HandlerFunc is automatically called after the Handler is executed.

type MiddlewareHandlerFunc

type MiddlewareHandlerFunc func(c *Context, next HandlerFunc)

HandlerFunc is an adapter to allow the use of ordinary functions as Negroni handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler object that calls f. type HandlerFunc func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)

func (MiddlewareHandlerFunc) ServeHTTP

func (h MiddlewareHandlerFunc) ServeHTTP(c *Context, next HandlerFunc)

type MuxHandlerAdapter

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

func NewMuxHandlerAdapter

func NewMuxHandlerAdapter(handler Handler) *MuxHandlerAdapter

func (*MuxHandlerAdapter) ServeHTTP

func (this *MuxHandlerAdapter) ServeHTTP(c interface{})

type Recovery

type Recovery struct {
	Logger     *log.Logger
	PrintStack bool
	StackAll   bool
	StackSize  int
}

Recovery is a Negroni middleware that recovers from any panics and writes a 500 if there was one.

func NewRecovery

func NewRecovery() *Recovery

NewRecovery returns a new instance of Recovery

func (*Recovery) ServeHTTP

func (rec *Recovery) ServeHTTP(c *Context, next HandlerFunc)

type Renderer

type Renderer interface {
	Render(c *Context, view string, model interface{})
}

Renderer interface used to render templates

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Flusher
	// Status returns the status code of the response or 0 if the response has not been written.
	Status() int
	// Written returns whether or not the ResponseWriter has been written.
	Written() bool
	// Size returns the size of the response body.
	Size() int
	// Before allows for a function to be called before the ResponseWriter has been written to. This is
	// useful for setting headers or any other operations that must happen before a response has been written.
	Before(func(ResponseWriter))
}

ResponseWriter is a wrapper around http.ResponseWriter that provides extra information about the response. It is recommended that middleware handlers use this construct to wrap a responsewriter if the functionality calls for it.

func NewResponseWriter

func NewResponseWriter(rw http.ResponseWriter) ResponseWriter

NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter

type RouterContext

type RouterContext struct {
	*mux.Router
}

RouterContext Wrap mux.Router to support ServeHTTP(*Context)

func NewRouter

func NewRouter() *RouterContext

NewRouter Create a new mux router adapter

func NewRouterBase

func NewRouterBase(router *mux.Router) *RouterContext

NewRouter Create a new mux router adapter

func (*RouterContext) ServeHTTP

func (this *RouterContext) ServeHTTP(c *Context)

Wrapped ServeHttp

type Session

type Session interface {
	SessionId() string
	Get(string) interface{}
	Set(string, interface{}) Session
	GetAll() map[string]interface{}
}

Session

type User

type User struct {
	UserId   string `mgo:"_id"`
	UserName string
	Password string
}

type UserManager

type UserManager interface {
	Login(username string, password string) (bool, error)
	Logout()
	Authenticated() bool
	UserId() string
	UserName() string
	Info() *User
}

User

type ViewModel

type ViewModel struct {
	Model interface{}
	User  UserManager
	Html  *Html
}

type Webapp

type Webapp struct {
	RenderEngine Renderer
	// contains filtered or unexported fields
}

Negroni is a stack of Middleware Handlers that can be invoked as an http.Handler. Negroni middleware is evaluated in the order that they are added to the stack using the Use and UseHandler methods.

func Classic

func Classic() *Webapp

Classic returns a new Negroni instance with the default middleware already in the stack.

Recovery - Panic Recovery Middleware Logger - Request/Response Logging

func New

func New(handlers ...MiddlewareHandler) *Webapp

New returns a new Negroni instance with no middleware preconfigured.

func (*Webapp) FileServer

func (this *Webapp) FileServer(path_prefix string, file_path string)

func (*Webapp) Get

func (this *Webapp) Get(path string, f func(*Context)) *mux.Route

func (*Webapp) Handle

func (this *Webapp) Handle(path string, handler Handler) *mux.Route

func (*Webapp) HandleFunc

func (this *Webapp) HandleFunc(path string, f func(*Context)) *mux.Route

func (*Webapp) Handlers

func (n *Webapp) Handlers() []MiddlewareHandler

Returns a list of all the handlers in the current Negroni middleware chain.

func (*Webapp) NewRoute

func (this *Webapp) NewRoute(f func(*Context)) *mux.Route

func (*Webapp) Post

func (this *Webapp) Post(path string, f func(*Context)) *mux.Route

func (*Webapp) Run

func (this *Webapp) Run(addr string)

Run is a convenience function that runs the negroni stack as an HTTP server. The addr string takes the same format as http.ListenAndServe.

func (*Webapp) ServeHTTP

func (n *Webapp) ServeHTTP(rw http.ResponseWriter, r *http.Request)

func (*Webapp) ServeHTTPContext

func (n *Webapp) ServeHTTPContext(c *Context)

func (*Webapp) SubRoute

func (this *Webapp) SubRoute(path string) *Webapp

func (*Webapp) Use

func (n *Webapp) Use(handler MiddlewareHandler)

Use adds a Handler onto the middleware stack. Handlers are invoked in the order they are added to a Negroni.

func (*Webapp) UseFunc

func (n *Webapp) UseFunc(handlerFunc func(c *Context, next HandlerFunc))

UseFunc adds a Negroni-style handler function onto the middleware stack.

func (*Webapp) UseHandler

func (n *Webapp) UseHandler(handler Handler)

UseHandler adds a http.Handler onto the middleware stack. Handlers are invoked in the order they are added to a Negroni.

func (*Webapp) UseHandlerFunc

func (n *Webapp) UseHandlerFunc(handlerFunc func(c *Context))

UseHandler adds a http.HandlerFunc-style handler function onto the middleware stack.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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